10

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

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

good! i forgot about passing a function as an argument to a filter
4

I find this simpler and more readable

index = ar.findIndex(e => e.id == 2);

Comments

2

Not sure why you need the original index, but you can add the original index as a new property to the object itself. E.g: write a filter to add the idx:

angular.module('yourModule', [])
.filter('addId', [function() {
    return function(arrObj) {
        for (var i = 0; i < arrObj.length; ++i) {
            arrObj[i].$$originalIdx = i;
        }
        return arrObj;
    };
}]);

Then you can get this expression in html:

{{ tabs | addIdx | filter:{id: 777} }}

Or in javascript:

$scope.getTabIndex = function(id){
    var el = $filter('filter')( addId(tabs) , { id: id })[0];
    var el_index = el.$$originalIdx;
    return el_index;        
};

Somehow I can't get it work on jsfiddle, it seems to have trouble with the dependencies injection..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.