Filtering array using $ .grep failed

[{"id":1,"name":"John"},{"id":2,"name":"James"},{"id":3,"name":"Alex"}]

$.grep(Arr.nameList, function(e){ 
    return e.id != 1; 
});

console.log(Arr.nameList);

      

I expect to get 2 arrays coming back from John discard, but I get them all back anyway, what's wrong with mine $.grep

above?

+3


source to share


2 answers


$.grep()

returns a new filtered array and does not affect the original array.

Try:

var filteredArray = $.grep(Arr.nameList, function(e){ 
    return e.id != 1; 
});    
console.log(filteredArray);

      



What you were doing was creating a new filtered array but ignoring it and checking the original unaffected array

Link: $. grep () docs

DEMO

0


source


jQuery.grep Description: Finds the elements of an array that satisfy a filter function. The original array is unaffected.

  • First you need to store the returned array in a variable.
  • Remove .nameList

    you don't need to add anything, just your array Arr

    .

Replace:

$.grep(Arr.nameList , function(e){ 
    return e.id != 1; 
});

      

By:



var result = $.grep(Arr , function(e){ 
    return e.id != 1; 
});

      

You can find the grep result:

console.log(result);

      

Take a look at Working Violin .

+1


source







All Articles