簡體   English   中英

比較對象javascript的兩個數組並刪除不相等的值

[英]Comparing two array of object javascript and remove values that are not equal

我有兩個對象數組。

e = [{uniqueId:'',active:'a',qId:10},{uniqueId:'',active:'a',qId:11}]
f = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}]

我想比較這些對象,我的最終結果將是

result = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11}]

我試過了

let result = e.filter(o1 => f.some(o2 => o1.qId != o2.qId));

但是越來越

[{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}]

如何達到期望的輸出?

看起來您應該過濾f而不是e ,因為result顯示的是f而不是e

為了使復雜度最小,請首先將e數組的qId轉換為Set以便快速查找。 (與.some O(N)復雜度相比, Set具有O(1)查找時間)

 const e = [{uniqueId:'',active:'a',qId:10},{uniqueId:'',active:'a',qId:11}] const f = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}] const qIds = new Set(e.map(({ qId }) => qId)); console.log(f.filter(({ qId }) => qIds.has(qId))); 

我希望您需要在qId上進行比較。

 let e = [{uniqueId:'',active:'a',qId:10},{uniqueId:'',active:'a',qId:11}] let f = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}] let res = []; f.forEach(fo => { e.forEach(eo => { if(fo.qId === eo.qId){ res.push(fo) } }) }) console.log(res) 

您可以結合使用Array.filter()Array.some()獲得該結果:

 e = [{uniqueId:'',active:'a',qId:10},{uniqueId:'',active:'a',qId:11}] f = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}]; var res = f.filter(fItem => e.some(({qId}) => fItem.qId === qId)); console.log(res); 

您可以檢查數組e是否具有相同的qId值來過濾f

 var e = [{ uniqueId: '', active: 'a', qId: 10 }, { uniqueId: '', active: 'a', qId: 11 }], f = [{ uniqueId: 50, active: 'a', qId: 10 }, { uniqueId: 51, active: 'a', qId: 11 }, { uniqueId: 52, active: 'a', qId: 13 }], result = f.filter(({ qId }) => e.some(o => o.qId === qId)); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM