【JS】Array.reduce对数组中的指定key求和

Array.prototype.sumFields = function(...fields) {
	return this.reduce((acc, item) => {
		fields.forEach(field => {
		  acc[field] = (acc[field] || 0) + (Number(item[field]) || 0);
		});
		return acc;
	  }, {});
}

const items = [
	{ a: 10, b: 20, c: null },
	{ a: 15, b: 25, c: '35' },
	{ a: 5, b: 20, c: 8.5 },
  ];

const acc = items.sumFields('a', 'c');
console.log(acc)

  运行结果:

zcm@TXK MINGW64 /d/sysProfile/Desktop
$ node a.js
{ a: 30, c: 43.5 }

  

posted on 2024-10-13 15:06  清清飞扬  阅读(6)  评论(0编辑  收藏  举报