如何统计给定JavaScript对象中值的出现次数并生成目标结果
统计JavaScript对象中值的出现次数
给定原始对象:
const obj1 = { 1: 'a', 2: 'b', 3: 'a', 4: 'c', 5: 'a', 6: 'd', 7: 'c', };
需要统计对象中各值的出现次数,最终得到结果:{ a: 3, b: 1, c: 2, d: 1 }
方法一:使用for...in循环遍历
这种方法兼容性强,适配所有JavaScript运行环境:
const countValueOccurrences = (obj) => { const result = {}; for (const key in obj) { // 仅遍历对象自身属性,排除原型链上的属性 if (obj.hasOwnProperty(key)) { const value = obj[key]; // 若当前值未统计过则初始化为0,再加1 result[value] = (result[value] || 0) + 1; } } return result; }; const output = countValueOccurrences(obj1); console.log(output); // 输出: { a: 3, b: 1, c: 2, d: 1 }
方法二:使用Object.values()结合reduce()
利用ES6 API实现更简洁的写法:
const output = Object.values(obj1).reduce((accumulator, currentValue) => { accumulator[currentValue] = (accumulator[currentValue] || 0) + 1; return accumulator; }, {}); console.log(output); // 输出: { a: 3, b: 1, c: 2, d: 1 }
Object.values()会提取对象的所有值并返回一个数组,reduce()遍历该数组,逐步累加每个值的出现次数,最终生成统计结果对象。
内容的提问来源于stack exchange,提问作者Gautham Shetty
相关产品推荐
相关产品推荐

