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'}]
Prabs
  • 117
  • 2
  • 11
  • 1
    Could you please edit the question to include what you've already tried. – Olian04 Aug 23 '19 at 14:45
  • I believe this could possibly be a [Duplicate?](https://stackoverflow.com/questions/57499126/filter-array-on-multiple-attributes-on-same-key/57499181#57499181) – bitznbytez Aug 23 '19 at 14:57

4 Answers4

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)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
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.

Ahmed Bajra
  • 391
  • 1
  • 2
  • 14
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);
Neel Rathod
  • 2,013
  • 12
  • 28
1
const wantedArr = firstArr.filter(({ id }) => secondArr.includes(`${id}`));
Dan
  • 8,041
  • 8
  • 41
  • 72