教程 lodash tutorial

_.intersectionWith([arrays], [comparator])

  • 解释: 这个函数接受多个数组作为参数,并接受一个自定义比较函数 comparator。它返回一个新数组,其中包含所有数组之间的交集,使用自定义比较函数来确定两个元素是否相等。

  • 应用举例:

javascript
const array1 = [
  { x: 1, y: 2 },
  { x: 2, y: 3 },
];
const array2 = [
  { x: 1, y: 1 },
  { x: 2, y: 2 },
];
const comparator = (a, b) => a.x === b.x;

const intersectionArray = _.intersectionWith(array1, array2, comparator);
console.log(intersectionArray); // 输出: [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 3 }]

在这个例子中,array1 和 array2 是包含对象的数组。通过调用 _.intersectionWith(array1, array2, comparator),使用自定义比较函数 comparator 来确定对象是否相等,获取了这两个数组之间的交集,即包含了具有相同 x 属性值的对象 [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 3 }]。