JavaScript removes objects from list based on an array of key values

Viewed 59

I'm trying to remove objects from an array based on their keys by passing in an array of keys.

For example, I have an array of objects called "clients":

[
  { id: 1, name: Tim },
  { id: 2, name: Bob },
  { id: 3, name: Joe },
]

Then I have another array with the keys called "ids":

[1,3]

After I filter it, I should be left with just:

[
  { id: 2, name: Bob },
]

So far I've tried this, but it returns everything:

filteredClients = clients.filter(n.id => !ids.includes(n.id)
3 Answers

Use n in your callback instead of n.id. In this case n will take the value of each object of the clients array on each iteration. More info here.

const clients = [
     {id:1,name:"Tim"},
     {id:2,name:"Bob"},
     {id:3,name:"Joe"}
];

const ids = [1, 3];

var filteredClients = clients.filter(n => !ids.includes(n.id));

console.log(filteredClients);

let arr = [
     {id:1,name:'Tim'},
     {id:2,name:'Bob'},
     {id:3,name:'Joe'},
]
let con = [1,3]


let updatedArr = arr.find((x)=> !con.includes(x.id));
console.log(updatedArr);

We can use .find along with includes function of array to filter out the unwanted objects from your array

Initial line of code:

filteredClients = clients.filter(n.id => !ids.includes(n.id)

The updated line of code should be:

filteredClients = clients.filter(n => !ids.includes(n.id))

Here instead of using n.id use n for callback in your lambda function. As in ES6 value of each object is taken by n in each iteration of given clients array

For more info here

Related