0

I have the following array:

  var arr = [{"userId":"12j219","name":"Harry"},{"userId":"232j32", "name":"Nancy"}]

I want to delete a whole object when the following condition is met:

userId == 12j219

For that, I've done the following:

arr.filter((user)=>{
    if(user.userId != "12j219"){
    return user;
    }
    })

It does the job, but for sure it does not delete anything. How can I delete the object from the array?

6
  • 2
    arr = arr.filter(...) Commented May 10, 2017 at 19:24
  • 1
    filter returns a new array. Commented May 10, 2017 at 19:24
  • @Alex nice catch ! it solves the issue, thanks ! Commented May 10, 2017 at 19:26
  • 1
    The filter function should return a boolean, not the user. So it could be simplified to filteredArray = arr.filter(user => user.userId !== '12j219'). Commented May 10, 2017 at 19:26
  • @MikeMcCaughan totally right, will look clean and simplified, thanks for the suggestion! Commented May 10, 2017 at 19:28

3 Answers 3

5

filter() returns a new array. From the docs:

Return value: A new array with the elements that pass the test.

You need assign the resultant array to arr variable.

Try:

var arr = [{"userId":"12j219","name":"Harry"},{"userId":"232j32", "name":"Nancy"}]
arr = arr.filter((user) => {
    return user.userId !== '12j219'
})
Sign up to request clarification or add additional context in comments.

Comments

1

If you have multiple references to the same array in different places of the code, you can just assign it to itself.

arr = arr.filter(user => user.userId !== "12j219");

Comments

0

Basically array filter iterates on all the elements from array, expects a true or false return. If false that element is removed and if true it stays.

var newArr = arr.filter(function(el){
    return el.userId != "12j219";
});

Comments

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.