admin管理员组

文章数量:1400375

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?

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?

Share Improve this question edited May 10, 2017 at 19:29 James 22.4k5 gold badges29 silver badges43 bronze badges asked May 10, 2017 at 19:23 Folky.HFolky.H 1,2044 gold badges16 silver badges40 bronze badges 6
  • 2 arr = arr.filter(...) – Alex Commented May 10, 2017 at 19:24
  • 1 filter returns a new array. – Evan Trimboli Commented May 10, 2017 at 19:24
  • @Alex nice catch ! it solves the issue, thanks ! – Folky.H 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'). – Heretic Monkey Commented May 10, 2017 at 19:26
  • @MikeMcCaughan totally right, will look clean and simplified, thanks for the suggestion! – Folky.H Commented May 10, 2017 at 19:28
 |  Show 1 more ment

3 Answers 3

Reset to default 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'
})

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");

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";
});

本文标签: JavaScriptRemove object from array when the condition is metStack Overflow