[英]How to filter array of objects with based on value from another array
I have two arrays, first containing objects and second containing ids. 我有两个数组,第一个包含对象,第二个包含id。 I want to return a new array from the first array that has ids from the first array. 我想从第一个数组返回一个新数组,该数组包含来自第一个数组的id。 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'}]
For linear time-complexity convert second array in to set and then use Set.prototype.has
对于线性时间复杂度,将第二个数组转换为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)
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
如果您想根据,以保持结果排列的顺序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)
You can achieve this with .indexOf()
or .includes()
method 您可以使用.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);
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. 我正在使用+e
将字符串转换为int,可能不是最好的方法,但肯定是最短的。
const wantedArr = firstArr.filter(({ id }) => secondArr.includes(`${id}`));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.