例如我们需要统计一个数组里每个工种的数量,电工有多少个人,木工有多少个人等等,这个数组里的数据是每个工人的信息,如下面的数据
const personArr = [
{
name: '张三',
workerIndustryType: '2',
workerIndustryTypeName: '电工'
},
{
name: '李四',
workerIndustryType: '2',
workerIndustryTypeName: '电工'
},
{
name: '王五',
workerIndustryType: '21',
workerIndustryTypeName: '木工'
},
{
name: '马六',
workerIndustryType: '21',
workerIndustryTypeName: '木工'
},
{
name: '李琦',
workerIndustryType: '1',
workerIndustryTypeName: '焊工'
},
{
name: '刘九',
workerIndustryType: '9',
workerIndustryTypeName: '瓦工'
}
];
可以用reduce函数来循环判断,如果有的话数量就+1,没有就是0,将数据进行聚合,统计同一种工种有多少次
const counts = personArr.reduce((pre, cur) => {
pre[cur.workerIndustryType] = (pre[cur.workerIndustryType] || 0) + 1;
return pre;
}, {});
console.log(counts); // {1: 1, 2: 2, 9: 1, 21: 2}
这样就可以统计出来了,如果需要用数组循环,可以通过Object.entries()来解耦得到一个新的数组
const arr = Object.entries(counts);

arr.png
然后通过for of循环这个新的数组来把每个工种的数量添加到一个新的数组中
const industryArr = [];
for (let [key, value] of arr) {
industryArr.push({
workerIndustryType: key,
count: value
});
}
console.log(industryArr);

industryType.png
下面是合到一起的代码
// 用reduce函数来循环判断,如果有的话就+1,没有就是0
// 将数据进行聚合,统计同一种工种有多少次
const counts = personArr.reduce((pre, cur) => {
pre[cur.workerIndustryType] = (pre[cur.workerIndustryType] || 0) + 1;
return pre;
}, {});
console.log(counts); // {1: 1, 2: 2, 9: 1, 21: 2}
// 如果需要用数组循环,可以通过Object.entries()来解耦数组得到一个新的数组
const arr = Object.entries(counts);
console.log(arr);
// 通过for of循环这个新的数组来把每个工种的数量添加到一个新的数组中
const industryArr = [];
for (let [key, value] of arr) {
industryArr.push({
workerIndustryType: key,
count: value
});
}
console.log(industryArr);