gpt4 book ai didi

javascript - 如何在n个对象数组中进行交集?

转载 作者:行者123 更新时间:2023-12-03 00:08:21 26 4
gpt4 key购买 nike

假设我们有一个对象数组

var users = [[
{ user: 'barney', age: 36, active: true },
{ user: 'fred', age: 41, active: true },
{ user: 'travis', age: 37, active: true }
], [
{ user: 'barney1', age: 36, active: true },
{ user: 'fred', age: 40, active: false },
{ user: 'travis', age: 37, active: true}
], [
{ user: 'barney1', age: 36, active: true },
{ user: 'fred', age: 40, active: false },
{ user: 'travis', age: 37, active: true}
]];

我想对上述对象应用交集。我努力了 与 lodash 方法交集,如

_.intersection(...users)

但它给出了一个空数组。

最佳答案

如果您想根据所有属性是否相同来将它们相交,请使用 intersectionWithisEqual

const users = [[{user:'barney',age:36,active:true},{user:'fred',age:41,active:true},{user:'travis',age:37,active:true}],[{user:'barney1',age:36,active:true},{user:'fred',age:40,active:false},{user:'travis',age:37,active:true}],[{user:'barney1',age:36,active:true},{user:'fred',age:40,active:false},{user:'travis',age:37,active:true}]]

const intersected = _.intersectionWith(...users, _.isEqual);

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

关于javascript - 如何在n个对象数组中进行交集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54864503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com