前言
使用js reduce()方法对多维对象数组内相同属性的值进行求和,并且计算出现的次数。
在写这个方法的过程中,了解到一个es7的方法,就是将多维数组转1维数组的方法
flat(params)
方法 不传参的话默认把二维数组转为一维数组要将多维数组转一维数组就需要传入
flat(Infinity)
第一,先了解一下flat()
转一维数组
// 多维数组求和并且合并为对应关系
const sum = [
[{
id: '350',
amount: '12',
}, {
id: '351',
amount: '134',
},
{
id: '352',
amount: '14',
},
{
id: '353',
amount: '48',
},
],
[{
id: '350',
amount: '20',
}, {
id: '354',
amount: '123',
},
{
id: '351',
amount: '1',
},
{
id: '355',
amount: '107',
},
[{
children:'44444'
}]
],
[
[{
children:'3'
}],
[{
children:'4'
}],
]
];
const one_dimensional = sum.flat(Infinity); //多维数组转一维数组
console.log(one_dimensional);
//flat() 不传参数时 不会将2维以上的多维数组转换
// (11) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, Array(1), Array(1), Array(1)]
//0: {id: '350', amount: '12'}
//1: {id: '351', amount: '134'}
//2: {id: '352', amount: '14'}
//3: {id: '353', amount: '48'}
//4: {id: '350', amount: '20'}
//5: {id: '354', amount: '123'}
//6: {id: '351', amount: '1'}
//7: {id: '355', amount: '107'}
//8: [{…}]
//9: [{…}]
//10: [{…}]
//length: 11
//[[Prototype]]: Array(0)
//flat(Infinity) 传参数时 不管几维数组都会转为一维数组
// (11) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
// 0: {id: '350', amount: '12'}
// 1: {id: '351', amount: '134'}
// 2: {id: '352', amount: '14'}
// 3: {id: '353', amount: '48'}
// 4: {id: '350', amount: '20'}
// 5: {id: '354', amount: '123'}
// 6: {id: '351', amount: '1'}
// 7: {id: '355', amount: '107'}
// 8: {children: '44444'}
// 9: {children: '3'}
// 10: {children: '4'}
// length: 11
// [[Prototype]]: Array(0)
第二,相同属性值求和以及计算次数
思路就是:先转一维数组,再求和以及计算出现次数
//原始数组的话,还是用第一步里边的`sum`数据
/**
* reduce()方法 将2维数组转为一维数组
* */
var single = sum.reduce((acc, cur) => {
return acc.concat(cur)
}, [])
/**
* flat()方法
* */
const one_dimensional = sum.flat(Infinity); //多维数组转一维数组
var peopleSums = one_dimensional.reduce(function(prev, cur) {
let sameAttribute = prev.find(i => i.id == cur.id)
let _object = {
...cur,
OccurrenceTimes: 1,
}
sameAttribute ? (sameAttribute.amount = sameAttribute.amount * 1 + cur.amount * 1, sameAttribute.OccurrenceTimes++) : prev.push(_object)
return prev;
}, []);
console.log(peopleSums);
// (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
// 0: {id: '350', amount: 32, OccurrenceTimes: 2}
// 1: {id: '351', amount: 135, OccurrenceTimes: 2}
// 2: {id: '352', amount: '14', OccurrenceTimes: 1}
// 3: {id: '353', amount: '48', OccurrenceTimes: 1}
// 4: {id: '354', amount: '123', OccurrenceTimes: 1}
// 5: {id: '355', amount: '107', OccurrenceTimes: 1}
// 6: {children: '44444', OccurrenceTimes: 3, amount: NaN}
// length: 7
// [[Prototype]]: Array(0)
在本篇博文中使用到es7的reduce()
方法,不了解的小伙伴请移步js ,数组求和,数组去重,es7 新增数组方法reduce()的用法详解
结束语
再平时开发中,经常遇到对对象数组内相同属性的值求和,这里记录一下方便自己学习和使用。