使用Lodash比较对象数组和整数数组

时间:2016-09-14 19:54:10

标签: javascript arrays object filter lodash

我有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吗?

4 个答案:

答案 0 :(得分:2)

首先,将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);

与天真的二次方法不同,这种方式的成本只是线性的(平均而言)。

答案 1 :(得分:2)

您可以使用chosen idperson 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); _.intersection的数组,通过_.map

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
{{1}}

答案 2 :(得分:1)

您可以使用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)

答案 3 :(得分:0)

您可以通过一次简化来完成这项工作;

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);