繁体   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