统计计算数组中的某个字段相同的数量

例如我们需要统计一个数组里每个工种的数量,电工有多少个人,木工有多少个人等等,这个数组里的数据是每个工人的信息,如下面的数据

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);
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容