3
[{"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 array returning back with John discard but I still get them all back, what's wrong with my $.grep above?

2 Answers 2

1

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

  1. First you have to store the returned array in variable.
  2. Remove .nameList you don't have 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 result of grep :

console.log(result);

Take a look at Working fiddle.

Sign up to request clarification or add additional context in comments.

2 Comments

that will completely replace the whole Arr object ... structure of which is not known
You are still making assumptions about namelist based on unknown information. Arr could be a big object with lots of properties
0

$.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 inspecting the original un-affected array

Reference: $.grep() docs

DEMO

1 Comment

ah my careless mistake, tq!

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.