数组中出现次数最多的数和出现的次数
作者:互联网
数组中出现次数最多的数和出现的次数
let arr = [44, 44, 44, 11, 22, 33, 22, 11, 22, 33, 44]
// 找出每个元素出现的次数
let newObj = arr.reduce((accumulatorObj, value) => {
accumulatorObj[value] ? accumulatorObj[value] = ++accumulatorObj[value] : accumulatorObj[value] = 1
return accumulatorObj
}, {})
// 获取出现最多的元素及次数(方式一)
let MaxKey = arr[0], maxValue = newObj[arr[0]]
for (const key in newObj) {
if (maxValue < newObj[key]) {
maxValue = newObj[key]
MaxKey = key
}
}
console.log(MaxKey, maxValue);
// 获取出现最多的元素及次数(方式二)
// let [[maxKey, maxValue]] = Object.entries(newObj).sort(([,value1], [, value2])=>value2 - value1)
// console.log('maxValue'+maxValue);
标签:arr,accumulatorObj,maxValue,value,newObj,次数,数组,出现 来源: https://blog.csdn.net/weixin_46873254/article/details/122603614