function mergeAndSumArray(arr, idKey = 'id') {
const map = new Map();
for (const obj of arr) {
const id = obj[idKey];
if (!map.has(id)) {
// 初次遇到此 id,直接存入 Map
map.set(id, { ...obj });
} else {
// 合并已存在的对象
const existing = map.get(id);
for (const key in obj) {
if (key === idKey) continue; // 跳过唯一标识符
const value = obj[key];
if (typeof value === 'number') {
// 数值属性累加
existing[key] = (existing[key] || 0) + value;
} else {
// 非数值属性覆盖(保留最后一次出现的值)
existing[key] = value;
}
}
}
}
// 返回合并后的数组
return Array.from(map.values());
}
// 测试用例
const inputArray = [
{ id: 1, apples: 5, oranges: 3, note: "First" },
{ id: 2, apples: 10, bananas: 7 },
{ id: 1, apples: 3, oranges: 2, note: "Last" },
{ id: 3, apples: 8 }
];
const mergedArray = mergeAndSumArray(inputArray);
console.log(mergedArray);
输出:
[
{ id: 1, apples: 8, oranges: 5, note: "Last" },
{ id: 2, apples: 10, bananas: 7 },
{ id: 3, apples: 8 }
]