返回
解析 Lodash-7 中 intersection, intersectionBy 和 intersectionWith 的用法
前端
2024-02-05 10:15:10
正文
intersection
intersection 函数用于计算两个数组的交集。它接收两个数组作为参数,并返回一个包含这两个数组中共同元素的新数组。
const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];
const intersectionResult = _.intersection(array1, array2);
console.log(intersectionResult); // [3, 4, 5]
intersectionBy
intersectionBy 函数与 intersection 函数类似,但它允许用户指定一个比较函数。比较函数用于比较两个数组中的元素,并根据比较结果决定哪些元素应该包含在交集数组中。
const array1 = [
{ name: 'John', age: 20 },
{ name: 'Mary', age: 25 },
{ name: 'Bob', age: 30 },
];
const array2 = [
{ name: 'Mary', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Alice', age: 35 },
];
const intersectionByResult = _.intersectionBy(array1, array2, (a, b) => a.name === b.name);
console.log(intersectionByResult); // [{ name: 'Mary', age: 25 }, { name: 'Bob', age: 30 }]
intersectionWith
intersectionWith 函数与 intersection 函数类似,但它允许用户指定一个谓词函数。谓词函数用于判断两个数组中的元素是否应该包含在交集数组中。
const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];
const intersectionWithResult = _.intersectionWith(array1, array2, (a, b) => a % 2 === 0 && b % 2 === 0);
console.log(intersectionWithResult); // [4]
总结
intersection、intersectionBy 和 intersectionWith 函数都是用于计算数组交集的工具函数。它们的区别在于 intersection 函数计算两个数组的交集,intersectionBy 函数根据给定的比较函数计算数组交集,而 intersectionWith 函数根据给定的谓词函数计算数组交集。希望本文能够帮助您理解这三个函数的用法和区别。