2

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)
Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
  • 1
    looks like it should work. But you need to only pass `n` in your lambda: `filteredClients = clients.filter(n => !ids.includes(n.id)` – Davin Tryon Mar 24 '20 at 16:03

3 Answers3

1

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);
vicpermir
  • 3,544
  • 3
  • 22
  • 34
0

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

Ram Sankhavaram
  • 1,218
  • 6
  • 11
0

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

matthias_h
  • 11,356
  • 9
  • 22
  • 40
saurav
  • 16
  • 1