,可以通过以下步骤实现:
sort()
方法,并传入一个比较函数来指定排序规则。以下是一个示例的JavaScript代码实现:
function intersectArraysByProperty(arr1, arr2, property) {
// Step 1: Sort arrays by property
arr1.sort((a, b) => a[property] - b[property]);
arr2.sort((a, b) => a[property] - b[property]);
// Step 2: Initialize result array
const result = [];
// Step 3: Initialize pointers
let pointer1 = 0;
let pointer2 = 0;
// Step 4-6: Intersect arrays by property
while (pointer1 < arr1.length && pointer2 < arr2.length) {
const obj1 = arr1[pointer1];
const obj2 = arr2[pointer2];
if (obj1[property] === obj2[property]) {
result.push(obj1);
pointer1++;
pointer2++;
} else if (obj1[property] < obj2[property]) {
pointer1++;
} else {
pointer2++;
}
}
// Step 7: Return result array
return result;
}
// Example usage
const arr1 = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
{ id: 3, name: 'C' }
];
const arr2 = [
{ id: 2, name: 'B' },
{ id: 3, name: 'C' },
{ id: 4, name: 'D' }
];
const intersectedArray = intersectArraysByProperty(arr1, arr2, 'id');
console.log(intersectedArray);
这段代码将根据对象的id
属性进行相交操作,返回两个数组相交后的对象数组。你可以根据实际情况修改属性名称和数据类型。
领取专属 10元无门槛券
手把手带您无忧上云