Syntactic Fructose
Syntactic Fructose

Reputation: 20076

$.grep returns empty array even when match occurs

I'm really confused why my grep function is not working. I have an array of objects like so:

$scope.kit = [{id: 1, producer: "company", category: "hardware" }, 
              {id: 2, producer: "company2", category: "hardware"}];

And i'm trying to remove id 2 using grep, I thought I would do:

$scope.kit = 
$.grep($scope.kit, function(e) {
    e.id != 2;
});

Yet, all I get is an empty array each time. What am I doing wrong here?

Upvotes: 0

Views: 1052

Answers (2)

trincot
trincot

Reputation: 349956

You are not returning the boolean expression. You should provide it as return value:

return  e.id != 2;

Without return, e.id != 2; doesn't do anything: the result of that expression disappears into oblivion. Then the return value of the $.grep callback function is undefined for all elements, which is falsy, and so none of the elements match, resulting in an empty array.

Upvotes: 3

Deep
Deep

Reputation: 9794

use return in grep function.

$.grep($scope.kit, function(e) {
    return e.id != 2;
});

As per the jquery docs http://api.jquery.com/jquery.grep/

The function should return a Boolean value

Upvotes: 1

Related Questions