犯罪嫌疑人X
我会在结果集中找到数组并更新所有值。var data = [["11-2019", 0, 20, 0, 0], ["11-2019", 41, 0, 0, 0], ["11-2019", 0, 0, 29, 0], ["11-2019", 0, 0, 0, 60], ["09-2019", 0, 1, 0, 0], ["09-2019", 0, 0, 1, 0], ["09-2019", 0, 0, 0, 1], ["05-2019", 2, 0, 0, 0]], result = data.reduce((r, a) => { var temp = r.find(([date]) => date === a[0]) if (temp) { for (var i = 1; i < a.length; i++) temp[i] += a[i]; } else { r.push([...a]); } return r; }, []);console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }
回首忆惘然
我filter在您的脚本中添加了 a以从结果中删除 0 值。如果你真的想要 0 值使用acc[curr[0]]=(acc[curr[0]]||[]).concat(curr.slice(1));反而。var inp=[["11-2019", 0, 20, 0, 0], ["11-2019", 41, 0, 0, 0], ["11-2019", 0, 0, 29, 0], ["11-2019", 0, 0, 0, 60], ["09-2019", 0, 1, 0, 0], ["09-2019", 0, 0, 1, 0], ["09-2019", 0, 0, 0, 1], ["05-2019", 2, 0, 0, 0]]; var out=inp.reduce((acc,curr)=>{ acc[curr[0]]=(acc[curr[0]]||[]).concat(curr.slice(1).filter(v=>v>0)); return acc }, {}); console.log(out); // and to get it into your format: var outarr=Object.keys(out).map(k=>[k].concat(out[k])) console.log(outarr)是的,如果你想要总和,那么我的版本如下。感谢 Nina 首先提供正确答案。;-)var inp=[["11-2019", 0, 20, 0, 0], ["11-2019", 41, 0, 0, 0], ["11-2019", 0, 0, 29, 0], ["11-2019", 0, 0, 0, 60], ["09-2019", 0, 1, 0, 0], ["09-2019", 0, 0, 1, 0], ["09-2019", 0, 0, 0, 1], ["05-2019", 2, 0, 0, 0]]; let out=inp.reduce((acc,cur)=>{ if(acc[cur[0]]) acc[cur[0]].forEach((v,i,a)=>a[i]+=cur[i+1]); else acc[cur[0]]=cur.slice(1) return acc }, {} ); outarr=Object.keys(out).map(k=>[k].concat(out[k])) console.log(outarr)