1. 数组内元素为一般数据类型
const arr1 = [1, 2, 3, 4, 5, 6, 7];
const arr2 = [11, 2, 33, 4, 55, 6, 77, 6, 6];
// arr1和arr2交集预计输出 [2, 4, 6]
交集代表两个数组中共同具有且不重复的值,因此我们可以借助 ES6 中 Set
值不重复的特性来操作:
/**
* @param { Array } a
* @param { Array } b
* @return { Array }
*/
function intersect(a, b) {
const setA = new Set(a);
const setB = new Set(b);
const intersection = [...setA].filter((item) => setB.has(item));
return a.filter((item) => intersection.includes(item));
}
intersect(arr1, arr2); // [2, 4, 6]
2. 数组内元素为复杂数据类型
const arr1 = [
{
name: "张三",
age: 18,
job: "门卫",
},
{
name: "李四",
age: 28,
job: "外卖小哥",
},
{
name: "老哥",
age: 38,
job: "快递员",
},
{
name: "大炮",
age: 35,
job: "电工",
},
];
const arr2 = [
{
name: "铁柱",
age: 35,
job: "司机",
},
{
name: "狗蛋",
age: 22,
job: "网红",
},
{
name: "老哥",
age: 38,
job: "快递员",
},
{
name: "阿牛",
age: 35,
job: "厨师",
},
];
// 已知name为唯一标识,按name取交集,预计输出结果为[{name: "老哥", age: 38, job: "快递员"}]
实现也只需要在原本的函数上稍加修改即可
/**
* @param { Array } a
* @param { Array } b
* @param { String } prop
* @return { Array }
*/
function intersectByProp(a, b, prop) {
const setA = new Set(a.map((item) => item[prop]));
const setB = new Set(b.map((item) => item[prop]));
const intersection = [...setA].filter((item) => setB.has(item));
return a.filter((item) => intersection.includes(item[prop]));
}
intersectByProp(arr1, arr2); // [{name: "老哥", age: 38, job: "快递员"}]
标签:const,name,item,交集,age,获取,job,数组,Array
From: https://www.cnblogs.com/ychizzz/p/17096353.html