ryanve
ryanve

Reputation: 52501

jQuery grep gripes

According to the $.grep() documentation I would think that the code below would print 2. But instead it's printing 0,1,2. See this fiddle. Am I going loco?

var arr = [0, 1, 2];

$.grep( arr, function(n,i) {
    return n > 1;
});

$('body').html( arr.join() );

Upvotes: 4

Views: 391

Answers (2)

Mike Robinson
Mike Robinson

Reputation: 25159

You're missing a key part.

"Description: Finds the elements of an array which satisfy a filter function. The original array is not affected."

var newArray = $.grep( arr, function(n,i) {
    return n > 1;
});

$('body').html( newArray.join() );

Upvotes: 3

Adam Rackis
Adam Rackis

Reputation: 83356

$.grep returns a new array - it doesn't modify your existing one.

You want

arr = $.grep( arr, function(n,i) {
    return n > 1;
});

Check out the $.grep docs for more information

Upvotes: 6

Related Questions