繁体   English   中英

如何使用基于另一个数组的值过滤对象数组

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

我有两个数组,第一个包含对象,第二个包含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'}]

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

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

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

这应该做的伎俩:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM