簡體   English   中英

使用Lodash比較對象數組和整數數組

[英]Using Lodash to Compare an Object Array and Integer Array

我有2條需要比較的數據:

人:

[
 {id:1, name:"Bill"},
 {id:2, name:"Sally"},
 {id:3, name:"Steve"},
 {id:4, name:"Rick"}
]

選擇:

[1,2,9,5]

我知道以下內容可以幫助我過濾具有所選數組中值的人員對象列表:

_(People).indexBy('id').at(chosen).value();

但是有可能做相反的事情嗎? 我可以過濾Chosen數組以僅包含來自People的ID嗎?

首先,將ID存儲在哈希中。 然后,篩選所選內容是微不足道的

 var hash = [ {id:1, name:"Bill"}, {id:2, name:"Sally"}, {id:3, name:"Steve"}, {id:4, name:"Rick"} ].reduce(function(hash,person) { hash[person.id] = true; return hash; }, Object.create(null)); var result = [1,2,9,5].filter(id => id in hash); console.log(result); 

與朴素的二次方方法不同,這種方式的成本僅是線性的(平均)。

你可以使用_.intersectionchosen ,並與數組idperson ,通過_.map

 var people = [{ id: 1, name: "Bill" }, { id: 2, name: "Sally" }, { id: 3, name: "Steve" }, { id: 4, name: "Rick" }], chosen = [1, 2, 9, 5], result = _.intersection(chosen, _.map(people, 'id')); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script> 

您可以使用filter()find()

 var arr = [ {id:1, name:"Bill"}, {id:2, name:"Sally"}, {id:3, name:"Steve"}, {id:4, name:"Rick"} ] var chosen = [1,2,9,5]; var result = chosen.filter(function(e) { return arr.find(o => o.id == e); }) console.log(result) 

您最好只做一次reduce。

 var arr = [ {id:1, name:"Bill"}, {id:2, name:"Sally"}, {id:3, name:"Steve"}, {id:4, name:"Rick"} ], chosen = [1,2,9,5], result = arr.reduce((res,o) => { var fi = chosen.indexOf(o.id); fi !== -1 && res.push(chosen[fi]); return res; },[]); console.log(result); 

暫無
暫無

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

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