33
$scope.data = [
    {
    "name": "Jim",
    "id" : 25
    },
    {
    "name": "Jerry",
    "id": 27
    },
    {
    "name": "Rithika",
    "id": 20
    }
    ];

    <div ng-repeat="person in data | filter: {id:20}">
        {{parent_index}}
    </div>

parent_index - Index of the filtered element in the actual array.

In this example, parent_index should return 2. how to find it?

4
  • Have you tried $index, iterator offset of the repeated element Commented Dec 24, 2013 at 7:29
  • please, provide more info about your question, its not clear and missed some data: what is parent_index, var data is out of scope and sure ng-repeat doesn't work Commented Dec 24, 2013 at 7:32
  • $index is returning zero. because filtered array has only one value [{"name" : "Rithika", "id" : 20 }] Commented Dec 24, 2013 at 7:36
  • @MaximShoustin question updated. let me know if it is not clear Commented Dec 24, 2013 at 7:38

3 Answers 3

81

find the index position of filtered value in the original array

Try this one:

<div ng-repeat="person in data | filter: {id:20}">
    {{data.indexOf(person)}}
</div>

Output: 2

Demo Fiddle

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

2 Comments

If you happen to be searching in a controller or service using $filter('filter'), then it returns an array of matches, so you can't just pass the result directly to indexOf. It my case I was filtering over a unique key, so I could safely do something like index = data.indexOf(person[0])
Hah! Thanks for the comment Parris Varney from December 9th - Parris Varney from May 9th was stuck on this same issue.
5

Here is a little helper function for finding index of an object in the array on given property value:

function getIndexOf(arr, val, prop) {
      var l = arr.length,
        k = 0;
      for (k = 0; k < l; k = k + 1) {
        if (arr[k][prop] === val) {
          return k;
        }
      }
      return false;
    }

example:

var arrOfobj = [
       {a:1, b:1, c:1}, //index 0
       {a:2, b:2, c:2}, //index 1
       {a:3, b:3, c:3} //index 2
    ];
var index = getIndexOf(arrOfobj, "2", "a");

Script above would result in index = 1 because property "a" has value 2 in second object in the array.

Comments

2

you can use $index value for loops.

<div ng-repeat="person in data | filter: {id:20}">{{$index+1}}<div>

1 Comment

This won't give you the index value in the original array only the filtered array.

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.