js统计数组中元素的重复次数(二)
let list = [
{name:"1000积分",serialNumber:6},
{name:"500积分",serialNumber:7},
{name:"50积分",serialNumber:8},
{name:"50积分",serialNumber:8},
{name:"50积分",serialNumber:8}
];
怎么把list数组转化为
[
{title:"1000积分",num:1},
{title:"500积分",num:1},
{title:"50积分",num:3}
]
//num:serialNumber相同的元素重复次数
let _res = [];
for(let i = 0; i < list.length;) {
let count = 0;
for(let j = i; j < list.length; j++) {
if(list[i].serialNumber == list[j].serialNumber) {
count++;
}
}
let obj = {
title:list[i].name,
num:count
}
_res.push(obj)
i += count;
}
console.log(_res)
//[{"title":"1000积分","num":1},{"title":"500积分","num":1},{"title":"50积分","num":3}]