1

I have two arrays, first containing objects and second containing ids. I want to return a new array from the first array that has ids from the first array. What is the best and efficient way to do this?

const firstArr = [{id: 1, city: London}, {id: 5, city: 'Berlin'}, {id: 10, city: 'Paris'}, {id: 2, city: 'Rome'}]

const secondArr = ['2', '5']

const wantedArr = [{id: 2, city: 'Rome'}, {id: 5, city: 'Berlin'}]
2
  • 1
    Could you please edit the question to include what you've already tried. Commented Aug 23, 2019 at 14:45
  • I believe this could possibly be a Duplicate? Commented Aug 23, 2019 at 14:57

4 Answers 4

3

For linear time-complexity convert second array in to set and then use Set.prototype.has

const firstArr = [{id: 1, city: 'London'}, {id: 5, city: 'Berlin'}, {id: 10, city: 'Paris'}, {id: 2, city: 'Rome'}]
const secondArr = ['2', '5'];

let set = new Set(secondArr);
const res = firstArr.filter(x => set.has(String(x.id)));

console.log(res)

If you want to keep the order of result array according to the secondArr then first make a object from firstArr and then use map() on secondArr

const firstArr = [{id: 1, city: 'London'}, {id: 5, city: 'Berlin'}, {id: 10, city: 'Paris'}, {id: 2, city: 'Rome'}]
const secondArr = ['2', '5'];

const obj = firstArr.reduce((ac,a) => (ac[a.id] = a,ac), {});

const res = secondArr.map(x => obj[x]);
console.log(res)

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

Comments

1

This should do the trick:

secondArr.map(e => firstArr.filter(a => a.id == +e))

I'm using +e to cast the string to an int, might not be the best way but certainly the shortest.

Comments

1

You can achieve this with .indexOf() or .includes() method

const firstArr = [{ id: 2, city: 'London' }, { id: 2, city: 'Tokyo' }, { id: 5, city: 'Berlin' }, { id: 10, city: 'Paris' }, { id: 6, city: 'Rome' }];

const secondArr = ['2', '5'];

const output = firstArr.filter((r) => {
  return secondArr.includes(`${r.id}`);
});

console.log(output);

const firstArr = [{ id: 2, city: 'London' }, { id: 2, city: 'Tokyo' }, { id: 5, city: 'Berlin' }, { id: 10, city: 'Paris' }, { id: 6, city: 'Rome' }];

const secondArr = ['2', '5'];

const output = firstArr.filter((r) => {
  return secondArr.indexOf(`${r.id}`) > -1;
});

console.log(output);

1 Comment

Happy to help :)
1
const wantedArr = firstArr.filter(({ id }) => secondArr.includes(`${id}`));

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.