其他分享
首页 > 其他分享> > js统计数组中元素的重复次数(二)

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;
}
//[{"title":"1000积分","num":1},{"title":"500积分","num":1},{"title":"50积分","num":3}]

标签:title,积分,serialNumber,list,js,次数,num,let,数组
来源: https://www.cnblogs.com/yixiancheng/p/12048722.html