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)
1
  • 1
    looks like it should work. But you need to only pass n in your lambda: filteredClients = clients.filter(n => !ids.includes(n.id) Commented Mar 24, 2020 at 16:03

3 Answers 3

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

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

Comments

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

Comments

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

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.