JS计算数组中每个元素出现的次数

时间:2025-01-20 19:53:49
// arr是需要解析的数组 let arr = [1, 2, 2, 2, 3, 3, 3]; //objGroup是输出的对象 let objGroup = arr.reduce(function (obj, name) { obj[name] = obj[name] ? ++obj[name] : 1; return obj; }, {}); //objKey是对象的键名构成的数组 let objKey = Object.keys(objGroup); //objValue是对象的值构成的数组 let objValue = Object.values(objGroup); console.log(objGroup);//{"1": 1, "2": 3, "3": 3} console.log(objKey);//["1", "2", "3"] console.log(objValue);//[1, 3, 3]

相关文章