如何基于另一个数组中的值来过滤对象数组

时间:2019-08-23 14:42:16

标签: javascript arrays

我有两个数组,第一个包含对象,第二个包含id。我想从第一个数组返回一个新数组,该数组具有第一个数组的ID。最佳和有效的方法是什么?

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

4 个答案:

答案 0 :(得分:4)

对于线性时间复杂度,将第二个数组转换为set,然后使用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)

如果要根据secondArr保持结果数组的顺序,请首先从firstArr创建对象,然后在map()上使用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)

答案 1 :(得分:2)

您可以使用.indexOf().includes()方法实现此目标

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

答案 2 :(得分:1)

这应该可以解决问题:

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

我正在使用+e将字符串转换为整数,这可能不是最好的方法,但肯定是最短的方法。

答案 3 :(得分:1)

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