1

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);
})
0

4 Answers 4

3

$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;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

care to explain why you would use findIndex instead of filter?
For speed. With the filter method, it will iterate the Tablelist twice. Once to find the correct item with the filter, and again in the indexOf. With findIndex it will only iterate once, and it will only be until it finds the first match.
A warning actually. I just realized that findIndex isn't supported in IE or Opera. You might be better off just using a for loop with a break when it finds a match.
2

Try this:

var object = $filter('filter')($scope.Tablelist, function (d) {
   return d.id === $scope.data.id;
})[0]
console.log(object);
console.log($scope.Tablelist.indexOf(object);

Comments

1
$filter('filter')($scope.Tablelist,{id: $scope.data.id},true) 

Returns a an array of length 1, not the item itself.

$filter('filter')($scope.Tablelist,{id: $scope.data.id},true)[0] 

may do the trick

Comments

1

$filter returns an array, you are trying to find index of that array in your Tablelist which returns -1, try:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.