JS/TS实现:统计对象数组指定属性值的出现次数并生成数组
JS/TS 对象数组统计指定属性唯一值及出现次数
需求
遍历对象数组,提取target属性的所有唯一值,生成一个包含[属性值, 出现次数]格式的数组。
原始数据
[ { name: "doesnt matter", target: "A", other: "doesnt matter" }, { name: "doesnt matter", target: "B", other: "doesnt matter" }, { name: "doesnt matter", target: "C", other: "doesnt matter" }, { name: "doesnt matter", target: "A", other: "doesnt matter" }, { name: "doesnt matter", target: "B", other: "doesnt matter" }, { name: "doesnt matter", target: "C", other: "doesnt matter" }, { name: "doesnt matter", target: "A", other: "doesnt matter" }, { name: "doesnt matter", target: "B", other: "doesnt matter" }, { name: "doesnt matter", target: "A", other: "doesnt matter" } ]
预期输出
const newArray = [['A', 4], ['B', 3], ['C', 2]]
尝试的代码(未达预期)
arr.reduce((accumulator: any, currentOrder: any) => { if (!accumulator[currentOrder[property]]) { accumulator[currentOrder[property]] = []; } accumulator[currentOrder[property]].push(currentOrder); return accumulator; }, []);
问题分析
这段代码有两个核心问题:
- 用数组作为累加器,但数组的键是数字索引,无法通过字符串(如"A")直接存取属性,导致统计逻辑错误;
- 把整个
currentOrder对象push进数组,最终得到的是分组后的对象数组,而非次数统计。
解决方案
完整实现代码
const arr = [ { name: "doesnt matter", target: "A", other: "doesnt matter" }, { name: "doesnt matter", target: "B", other: "doesnt matter" }, { name: "doesnt matter", target: "C", other: "doesnt matter" }, { name: "doesnt matter", target: "A", other: "doesnt matter" }, { name: "doesnt matter", target: "B", other: "doesnt matter" }, { name: "doesnt matter", target: "C", other: "doesnt matter" }, { name: "doesnt matter", target: "A", other: "doesnt matter" }, { name: "doesnt matter", target: "B", other: "doesnt matter" }, { name: "doesnt matter", target: "A", other: "doesnt matter" } ]; // 1. 用对象做累加器统计每个target值的出现次数 const countObj = arr.reduce((acc, item) => { const targetVal = item.target; acc[targetVal] = (acc[targetVal] || 0) + 1; return acc; }, {} as Record<string, number>); // 2. 将统计对象转为目标二维数组格式 const newArray = Object.entries(countObj); console.log(newArray); // 输出: [['A', 4], ['B', 3], ['C', 2]]
简化一行版
const newArray = Object.entries(arr.reduce((acc, {target}) => (acc[target] = (acc[target] || 0) + 1, acc), {} as Record<string, number>));
内容的提问来源于stack exchange,提问作者RooksStrife
相关产品推荐
相关产品推荐

