[英]Using Lodash to Compare an Object Array and Integer Array
I have 2 pieces of data that need to be compared: 我有2条需要比较的数据:
People: 人:
[
{id:1, name:"Bill"},
{id:2, name:"Sally"},
{id:3, name:"Steve"},
{id:4, name:"Rick"}
]
Chosen: 选择:
[1,2,9,5]
I know the following can help me filter a list of people objects that have values from the chosen array: 我知道以下内容可以帮助我过滤具有所选数组中值的人员对象列表:
_(People).indexBy('id').at(chosen).value();
But is it possible to do the reverse? 但是有可能做相反的事情吗? Can I filter the
Chosen
array to only contain the id's from People
? 我可以过滤
Chosen
数组以仅包含来自People
的ID吗?
First, store the IDs in a hash. 首先,将ID存储在哈希中。 Then, filtering the chosen is trivial
然后,筛选所选内容是微不足道的
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);
Unlike the naive quadratic approach, this way the cost is only linear (on average). 与朴素的二次方方法不同,这种方式的成本仅是线性的(平均)。
You could use _.intersection
with chosen
and an array with the id
of person
, via _.map
. 你可以使用
_.intersection
与chosen
,并与数组id
的person
,通过_.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>
You can do this with filter()
and find()
您可以使用
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)
You might as well do this job with a single reduce; 您最好只做一次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.