如何对第一个值(字符串)进行分组并添加相同日期的值?

JAVASCRIPT - JQUERY 对值求和 如何对第一个值(日期)进行分组并添加相同日期的值?


大批 :


0: (5) ["11-2019", 0, 20, 0, 0]

1: (5) ["11-2019", 41, 0, 0, 0]

2: (5) ["11-2019", 0, 0, 29, 0]

3: (5) ["11-2019", 0, 0, 0, 60]

4: (5) ["09-2019", 0, 1, 0, 0]

5: (5) ["09-2019", 0, 0, 1, 0]

6: (5) ["09-2019", 0, 0, 0, 1]

7: (5) ["05-2019", 2, 0, 0, 0]

出去 :


0: (5) ["11-2019", 41, 20, 29, 60]

1: (5) ["09-2019", 0, 1, 1, 1]

2: (5) ["05-2019", 2, 0, 0, 0]

result = DataAll.reduce(function(r, a) {

     a.forEach(function(b, i) {


         r[i] = (r[i] || 0) + b;

         console.log(r[i]);

     });

     return r;

 }, []);


largeQ
浏览 110回答 2
2回答

犯罪嫌疑人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]],&nbsp; &nbsp; result = data.reduce((r, a) => {&nbsp; &nbsp; &nbsp; &nbsp; var temp = r.find(([date]) => date === a[0])&nbsp; &nbsp; &nbsp; &nbsp; if (temp) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (var i = 1; i < a.length; i++) temp[i] += a[i];&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; r.push([...a]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return r;&nbsp; &nbsp; }, []);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],&nbsp;["11-2019", 41, 0, 0, 0],&nbsp;["11-2019", 0, 0, 29, 0],&nbsp;["11-2019", 0, 0, 0, 60],&nbsp;["09-2019", 0, 1, 0, 0],&nbsp;["09-2019", 0, 0, 1, 0],&nbsp;["09-2019", 0, 0, 0, 1],&nbsp;["05-2019", 2, 0, 0, 0]];&nbsp;var out=inp.reduce((acc,curr)=>{&nbsp; &nbsp;acc[curr[0]]=(acc[curr[0]]||[]).concat(curr.slice(1).filter(v=>v>0));&nbsp; &nbsp;return acc&nbsp;}, {});&nbsp; console.log(out);&nbsp;&nbsp;&nbsp; // and to get it into your format:&nbsp; var outarr=Object.keys(out).map(k=>[k].concat(out[k]))&nbsp; console.log(outarr)是的,如果你想要总和,那么我的版本如下。感谢 Nina 首先提供正确答案。;-)var inp=[["11-2019", 0, 20, 0, 0],&nbsp;["11-2019", 41, 0, 0, 0],&nbsp;["11-2019", 0, 0, 29, 0],&nbsp;["11-2019", 0, 0, 0, 60],&nbsp;["09-2019", 0, 1, 0, 0],&nbsp;["09-2019", 0, 0, 1, 0],&nbsp;["09-2019", 0, 0, 0, 1],&nbsp;["05-2019", 2, 0, 0, 0]];&nbsp;&nbsp;let out=inp.reduce((acc,cur)=>{&nbsp; &nbsp;if(acc[cur[0]]) acc[cur[0]].forEach((v,i,a)=>a[i]+=cur[i+1]);&nbsp; &nbsp;else acc[cur[0]]=cur.slice(1)&nbsp; &nbsp;return acc&nbsp;}, {} );&nbsp;outarr=Object.keys(out).map(k=>[k].concat(out[k]))&nbsp;&nbsp;console.log(outarr)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript