AngularJS:查找原始数组中过滤值的索引位置

时间:2021-05-16 21:28:06
$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.

parent_index -在实际数组中过滤的元素的索引。

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

在本例中,parent_index应该返回2。如何找到它吗?

3 个解决方案

#1


76  

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

输出:2

Demo Fiddle

演示小提琴

#2


4  

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.

上面的脚本将导致index = 1,因为属性“a”在数组的第二个对象中有值2。

#3


3  

you can use $index value for loops.

可以对循环使用$index值。

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

#1


76  

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

输出:2

Demo Fiddle

演示小提琴

#2


4  

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.

上面的脚本将导致index = 1,因为属性“a”在数组的第二个对象中有值2。

#3


3  

you can use $index value for loops.

可以对循环使用$index值。

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