Prabs
Prabs

Reputation: 127

How to filter array of objects with based on value from another array

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'}]

Upvotes: 1

Views: 83

Answers (4)

Dan
Dan

Reputation: 8784

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

Upvotes: 1

Neel Rathod
Neel Rathod

Reputation: 2111

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

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36564

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)

Upvotes: 3

Ahmed Bajra
Ahmed Bajra

Reputation: 401

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.

Upvotes: 1

Related Questions