>我有一个包含对象的数组数组:
let data = [[{a:0}, {b:1}], [{a:1}, {b:1}]]
现在我想对这两个数组进行一个 lodash 交集,返回[{b:1}]
当我这样做时:
import {intersection} from 'lodash'
return intersection([{a:0}, {b:1}], [{a:1}, {b:1}])
结果是正确的。
但是当我这样做时
return intersection(data)
我只是得到相同的结果。
有没有一种简单的方法将所有数组从数据传递到交集函数?我最初的想法是使用 .map,但这返回了另一个数组......
你可以把数组展开。
intersection(...arrayOfarrays);
或者,在 ES6 之前的环境中,使用应用:
intersection.apply(null, arrayOfArrays);
或者,您可以将intersect
转换为具有展开参数的函数:
const intersectionArrayOfArrays = _.spread(_.intersection);
intersectionArrayOfArrays(arrayOfArrays);
<小时 />请注意,lodash 中的交集不会自动处理对象数组。
如果你想在属性上相交,你可以使用 intersectionBy b
:
const arrayOfArrays = [[{a:0}, {b:1}], [{a:1}, {b:1}]];
console.log(
_.intersectionBy(...arrayOfArrays, 'b')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
或 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)
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>