輸入陣列:
[['1','a','b'], ['2','a','c'], ['2','a','b'], ['3','a','b'], ['2','a','c']]
需求:第 2、3 個元素相同時,將第 1 個元素(數值字串)相加,輸出:
[['6','a','b'], ['4','a','c']]
const arr = [['1','a','b'], ['2','a','c'], ['2','a','b'], ['3','a','b'], ['2','a','c']];
const map = {};
for (const [val, k1, k2] of arr) {
const key = k1 + '|' + k2; // 組合鍵,避免直接拼接衝突
map[key] = (map[key] || 0) + parseInt(val, 10);
}
const result = Object.entries(map).map(([key, sum]) => {
const [k1, k2] = key.split('|');
return [String(sum), k1, k2];
});
console.log(result); // [['6','a','b'], ['4','a','c']]
Map 或普通物件以「第2+第3元素」為鍵累加。parseInt(val, 10) 確保數值相加而非字串拼接。| 或 \0 避免 'ab'+'c' === 'a'+'bc' 衝突。const res = [...arr.reduce((m, [v, a, b]) => m.set(a+'|'+b, (m.get(a+'|'+b)||0)+ +v), new Map())]
.map(([k, v]) => [String(v), ...k.split('|')]);
掌握「分組鍵組合 + 累加器」模式,可高效處理各類陣列聚合需求。