Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: find the index position of filtered value in the original array

$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?

like image 292
Thilaga Avatar asked Dec 24 '13 07:12

Thilaga


2 Answers

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

like image 174
Maxim Shoustin Avatar answered Oct 09 '22 19:10

Maxim Shoustin


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.

like image 5
Gawran Avatar answered Oct 09 '22 20:10

Gawran