Joseph Goh Joseph Goh - 10 months ago 198
AngularJS Question

Angularjs get indexOf through filter

I have a set of JSON data returned by the backend API, and i need to loop through existing array and get the

to be used in
, thus i am using
method combined with the filter function from angular.

I am able to filter the data out from existing array, however i am unable to get the index of the array, it returned

This is how do it.


angular.forEach($, function(){
var index = $scope.Tablelist.indexOf($filter('filter')($scope.Tablelist,{id: $},true));
console.log($filter('filter')($scope.Tablelist,{id: $},true));


$filter returns an array, from which you need to get the first element, and then search with indexOf:

var index = $scope.Tablelist.indexOf(
                $filter('filter')($scope.Tablelist,{id: $},true)[0]

However, I would just use Array.prototype.findIndex(). It will be much faster, since it won't iterate the Tablelist more than it needs to.

var index = $scope.Tablelist.findIndex(function(item) {
    return === $;

Or a regular for loop if you want better browser compatibility:

var index = -1;
for (var i = 0; i < $scope.Tablelist.length; i++)
    if ($scope.Tablelist[i].id === $ {
        index = i;