Get element's index after using filter

Ivan Chernykh picture Ivan Chernykh · Sep 27, 2013 · Viewed 10k times · Source

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 );

http://jsfiddle.net/BhxVV/

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;        
 }

http://jsfiddle.net/BnBCS/1/

But it is too long and i'm sure that i'm reinventing the wheel here...

Answer

Maxim Shoustin picture Maxim Shoustin · Sep 27, 2013

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