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

只愿长相守 提交于 2019-11-29 06:07:17

问题


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


回答1:


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




回答2:


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.




回答3:


you can use $index value for loops.

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


来源:https://stackoverflow.com/questions/20756694/angularjs-find-the-index-position-of-filtered-value-in-the-original-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!