如何相交n个数组对象?

时间:2019-02-25 10:48:43

标签: javascript ecmascript-6 lodash javascript-objects

假设我们有一个对象数组

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)

但是它给出了一个空数组。

2 个答案:

答案 0 :(得分:1)

如果要基于所有属性是否相同来相交,请使用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>

答案 1 :(得分:0)

您不能使用_.intersection(),因为它只会比较数组中的对象引用。您必须告诉相交方法如何比较项目。

为此,请使用_.intersectionBy()_.intersectionWith()方法,为其赋予要相交的数组,并作为最后一个参数使用该属性来检查相交。

根据对象的结构和使用方式,您的用户对象应为数组(2D):

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 result = _.intersectionBy(...users, 'user');

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

您还可以使用Array.reduce()Array.filter()Array.some()使用纯JavaScript:

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 intersect = (arrays, comp) => {
  return arrays.reduce((acc, arr) => acc.filter(i => arr.some(j => comp(i, j))));
};

console.log(intersect(users, (a, b) => a.user === b.user));