2

say I have a list of objects like so.

const list = [{id: 1, name: "foo"}, {id: 2, name: "bar"}, {id: 3, name: "baz"}]

And then I have a list of items I'd like to find in said list.

const ids = [1, 3]

how can I return an array of objects that match the ids found in ids from list using javascript?

heres an example of the return I'd like to see given I have [1, 3].

-> [{id: 1, name: "foo"}, {id: 3, name: "baz"}]

Thanks - Josh

1
  • 1
    list.filter(({ id }) => ids.includes(id)) Commented Jul 13, 2018 at 22:56

2 Answers 2

5

You can do it via filter method, which returns new array of items, based on condition you wrote inside. I also recommend to use includes method to check, whether your array of ids has such item:

const list = [{id: 1, name: "foo"}, {id: 2, name: "bar"}, {id: 3, name: "baz"}];
const ids = [1, 3];
const newArr = list.filter(item => ids.includes(item.id));
console.log(newArr);

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

Comments

0

You can do it with map and find:

const list = [{id: 1, name: "foo"}, {id: 2, name: "bar"}, {id: 3, name: "baz"}];
const ids = [1, 3];
const newArr = ids.map(i => list.find(({id}) => i === id));
console.log(newArr);

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.