Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element's index after using filter

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...

like image 917
Ivan Chernykh Avatar asked Sep 27 '13 12:09

Ivan Chernykh


2 Answers

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

like image 159
Maxim Shoustin Avatar answered Nov 02 '22 14:11

Maxim Shoustin


I find this simpler and more readable

index = ar.findIndex(e => e.id == 2);
like image 34
Emanuel Avatar answered Nov 02 '22 14:11

Emanuel