将一个数组数组传递给lodash交集

Mih*_*šič 5 javascript ecmascript-6 lodash

我有一个包含对象的数组数组:

let data = [[{a:0}, {b:1}], [{a:1}, {b:1}]]
Run Code Online (Sandbox Code Playgroud)

现在我想要做这两个数组的lodash交集,返回[{b:1}]

当我这样做:

import {intersection} from 'lodash'

return intersection([{a:0}, {b:1}], [{a:1}, {b:1}])
Run Code Online (Sandbox Code Playgroud)

结果是对的.

但是,当我这样做

return intersection(data)
Run Code Online (Sandbox Code Playgroud)

我刚刚得到相同的结果.

有没有一种简单的方法可以将所有数组从数据传递到交集函数?我最初的想法是使用.map,但这会返回另一个数组......

nem*_*035 13

你可以只传播阵列.

intersection(...arrayOfarrays);
Run Code Online (Sandbox Code Playgroud)

或者,在ES6之前的环境中,使用apply:

intersection.apply(null, arrayOfArrays);
Run Code Online (Sandbox Code Playgroud)

或者,您可以转换intersect为具有展开参数的函数:

const intersectionArrayOfArrays = _.spread(_.intersection);
intersectionArrayOfArrays(arrayOfArrays);
Run Code Online (Sandbox Code Playgroud)

请注意,尽管lodash 中的交集不会自动处理对象数组.

如果要在属性上相交,可以使用intersectionByb:

const arrayOfArrays = [[{a:0}, {b:1}], [{a:1}, {b:1}]];
console.log(
  _.intersectionBy(...arrayOfArrays, 'b')
)
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

intersectionWith,如果你想通过引用或深度比较在相同的对象上相交:

const a1 = {a: 0};
const a2 = {a: 1};
const b = {b: 1};
const arrayOfArrays = [[a1, b], [a2, b]];

// reference comparison
console.log(
  _.intersectionWith(...arrayOfArrays, (a, b) => a === b)
)

// deep equality comparison
console.log(
  _.intersectionWith(...arrayOfArrays, _.isEqual)
)
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Run Code Online (Sandbox Code Playgroud)