Joseph Goh Joseph Goh - 6 months ago 133
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

index
to be used in
splice
, thus i am using
indexOf
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
-1
.

This is how do it.

JS

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

Answer

$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: $scope.data.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 item.id === $scope.data.id;
});

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 === $scope.data.id) {
        index = i;
        break;
    }
}