I have an array with objects. I want to find a specific object's index. This object has an unique id
property' value , and i can find it with a $filter
:
var el = $filter('filter')( tabs, { id: id })[0]; // "el" is my unique element
But how can i know what is the index of this element in it's original array? Does $filter
can provide me this information?
By now i didn't find an Angular solution, because i can't get much useful info on this page. So i have used Array
's indexOf
method :
var el_index = tabs.indexOf( el );
To get indexes of all elements with specific id
we go the similar way:
$scope.getTabsIndexes = function(id){
var els = $filter('filter')( tabs , { id: id });
var indexes = [];
if(els.length) {
var last_i=0;
while( els.length ){
indexes.push( last_i = tabs.indexOf( els.shift() , last_i ) );
}
}
return indexes;
}
But it is too long and i'm sure that i'm reinventing the wheel here...
Try this option:
$scope.search = function(selectedItem) {
$filter('filter')($scope.tabs, function(item) {
if(selectedItem == item.id){
$scope.indexes.push( $scope.tabs.indexOf(item) );
return true;
}
return false;
});
}
I think it a bit short and clear.
See Fiddle