获取数组中出现最多的元素
1、方法一:需要三次循环,缺点:大量的循环操作会消耗大量的计算资源、代码多
const arr = ['a', 'c', 'b', '1', '9', 'b', 'sdf', '6', 'b', 'aaaa', '汉字', '汉字', 'sdf', '-', '-']
const obj = {}
arr.forEach(item => {
if (obj[item]) {
obj[item]++
} else {
obj[item] = 1
}
})
const numArr = []
for (const item in obj) {
numArr.push(obj[item])
}
const sortNum = numArr.sort((a, b) => {
return b - a
})
for (const item in obj) {
if (obj[item] === sortNum[0]) {
console.log('出现最多的元素和次数', item, obj[item])
}
}
2、一次循环,使用二维数组处理元素集合
const arr = ['a', 'a', 'c', 'b', '1', '9', 'b', 'sdf', '6', 'b', 'aaaa', '汉字', '汉字', 'sdf', '-', '-'] const obj = {} const newArr = [] let d = 0 let dStr = '' arr.forEach(item => { if (obj[item] === undefined) { newArr.push([]) const index = newArr.length - 1 obj[item] = index } newArr[obj[item]].push(item) const newItem = newArr[obj[item]] if (newItem.length > d) { d = newItem.length dStr = newItem[0] } }) console.log('新数组', newArr) console.log('出现最多的元素和次数:', dStr, d)