Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() );
like image 596
ryanve Avatar asked Jan 18 '23 23:01

ryanve


2 Answers

$.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

like image 192
Adam Rackis Avatar answered Jan 28 '23 23:01

Adam Rackis


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() );
like image 22
Mike Robinson Avatar answered Jan 29 '23 00:01

Mike Robinson