gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:46:55 25 4
gpt4 key购买 nike

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

关于javascript - 如何基于另一个数组中的值过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57628489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com