如何使用lodash获取交集?

15

我试图返回这个对象数组中匹配的id:

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1"]

我怎样才能返回数组 arr 中值为 1 的 id?

1个回答

36

Lodash

使用lodash的_.intersectionBy可能是最简洁且有效的解决方案,但需要确保你的arr2数组包含一个带有id属性的对象:

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =[{id:1}]  // <-- object with the `id`

const result = _.intersectionBy(arr, arr2, 'id');

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

使用lodash另一种方式是通过_.intersectionWith,它不需要对给定的输入进行任何更改:

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1"]

const result = _.intersectionWith(arr, arr2, (o,num) => o.id == num);

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

这个想法是提供一个自定义函数,让它知道如何比较两个数组之间的值。

ES6和纯Javascript

如果你只想查找一个项目,那么你可以只使用JS通过Array.find来实现:

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1"]

const result = arr.find(x => arr2.some(y => x.id == y))
console.log(result)

如果您的arr2中有更多的id,您可以使用Array.filter

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1", "2"]

const result = arr.filter(x => arr2.some(y => x.id == y))
console.log(result)

你已经在数组中拥有id,因此也可以直接使用 Array.map

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1"]

const result = arr2.map(x => arr.find(y => y.id == x))
console.log(result)

正如 @ibrahim mahrir 提到的另一个选项,可以通过 Array.findArray.includes 来实现:

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1"]

const result = arr.filter(x => arr2.includes(x.id.toString()))
console.log(result)


1
或者简单地使用 arr.find(x => arr2.includes("" + x.id)),如果 arr2 包含数字,则可以进一步简化为 arr.find(x => arr2.includes(x.id)) - ibrahim mahrir
当然,好主意。不太确定我想要简化多少,但既然你提到了,我现在会这么做 :) - Akrion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接