簡體   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