如何正确统计属性出现次数并将其存入原数组?
问题描述
我想要统计数组中year和id属性的总出现次数,并将统计结果存入一个新的count字段中。目前已实现数组简化和次数统计,但无法将统计结果合并到原数组中。我通过将id和year序列化为字符串来统计次数,但由于JavaScript将计数器保存为对象且键为序列化后的字符串,无法直接添加到原数组。
现有代码如下:
const keys_to_keep = ["year", "id"]; const reduceData = (unprocessedData) => unprocessedData.map(entry => keys_to_keep.reduce((acc, curr) => { acc[curr] = entry[curr]; return acc; }, {})); const newData = reduceData(data); // count where id and year the same: counter = {} newData.forEach(function (obj) { var key = JSON.stringify(obj) counter[key] = (counter[key] || 0) + 1 })
数组结构:
[{ year: 1994, id: 123 }, { year: 1994, id: 123 }, { year: 1998, id: 124 }]
期望得到的结果:
[{ year: 1994, id: 123, count: 2 }, { year: 1994, id: 123, count: 2 }, { year: 1998, id: 124, count: 1 }]
解决方案
你可以直接基于原数组生成计数器,再遍历原数组给每个元素添加count字段,省去多余的数组转换步骤,具体实现如下:
步骤1:生成计数器对象
遍历原数组,用year和id拼接成唯一标识作为键,统计每组的出现次数:
const counter = {}; data.forEach(item => { // 用年份+ID拼接成唯一键,比JSON.stringify更高效 const key = `${item.year}-${item.id}`; counter[key] = (counter[key] || 0) + 1; });
步骤2:给原数组元素添加count字段
遍历原数组,复制每个元素并添加对应的count值,避免修改原数组:
const result = data.map(item => { const key = `${item.year}-${item.id}`; return { ...item, count: counter[key] }; });
完整整合代码
const data = [{ year: 1994, id: 123 }, { year: 1994, id: 123 }, { year: 1998, id: 124 }]; // 生成计数器 const counter = {}; data.forEach(item => { const key = `${item.year}-${item.id}`; counter[key] = (counter[key] || 0) + 1; }); // 生成带count字段的结果数组 const result = data.map(item => ({ ...item, count: counter[`${item.year}-${item.id}`] })); console.log(result);
如果坚持使用JSON.stringify作为键,只需把拼接的key替换为JSON.stringify({year: item.year, id: item.id})即可,效果一致。
内容的提问来源于stack exchange,提问作者FishyK
相关产品推荐
相关产品推荐

