检测数组中出现最多次数的元素及次数
收集大佬们的写法
-
有个Bug,如果刚好有两个或者两个以上的最多次数,这个只能找到第一次的
let arr1 = [1,2,2,3,4,5,6,6,7,7,7,7,7,7,7];
let arr2 = [1,2,2,2,3,3,4,7,7,4,3,3,1];
function getMaxAmount(data){
let obj = {
};
data.forEach(val => {
obj[val] = obj[val] ? obj[val] + 1 : 1
})
let num = 0; // 出现最多的数字
let frequency = 0; // 出现最多的次数
for(let key in obj){
if(obj[key] > frequency){
num = key;
frequency = obj[key];
}
}
return num + + frequency
}
console.log(getMaxAmount(arr3)) // 7 7 出现最多的数字 出现最多的次数
console.log(getMaxAmount(arr2)) // 3 4
-
这一种堪称完美
// 检测数组中出现最多次数的元素及次数
let arr1 = [1,2,2,3,4,5,6,6,7,7,7,7,7,7,7];
let arr2 = [1,2,2,2,3,3,4,7,7,4,3,3,1];
let arr3 = [1,2,3,3,5,7,7,9,6,6];
function getMaxAmount(arr){
if(!arr.length){
return 不要传空数组忽悠我!;
}
let store = new Map();
let result = {
key:[],
value:0,
};
arr.forEach(item=>{
store[item] ? (store[item]++) : (store[item] = 1);
let val = store[item];
if(val > result.value){
result.key = [item];
result.value = val;
}else if(val === result.value){
result.key.push(item);
}
});
return 数组中出现次数最多的元素是+result.key.join(、)+,出现了+result.value + 次。
}
console.log(getMaxAmount(arr3)) // 数组中出现次数最多的元素是3、7、6,出现了2次。
console.log(getMaxAmount(arr2)) // 数组中出现次数最多的元素是3,出现了4次。
-
reduce 累加器
let arr3 = [1,2,3,3,5,7,7,9,6,6];
const count = arr3.reduce((prev,cur)=>{
if(cur in prev){
prev[cur]++;
}else{
prev[cur]=1;
}
return prev
},{
})
console.log(count) // 输出元素与次数 {1: 1, 2: 1, 3: 2, 5: 1, 6: 2, 7: 2, 9: 1}
-
es5
let arr3 = [1,2,3,3,5,7,7,9,6,6];
function getMaxAmount(arr){
let hashTable = {
},
max = 0;
for(let i = 0; i < arr.length; i++){
if(!(arr[i] in hashTable)){
hashTable[arr[i]] = 1;
}else {
hashTable[arr[i]] += 1;
}
if(arr[i] > max){
max = arr[i];
}
}
let maxVal = 0;
for(let j = 0; j <= max; j++){
if(j in hashTable){
if(hashTable[j] > maxVal){
maxVal = hashTable[j]
}
}
}
for(let j=0; j<= max; j++){
if(hashTable[j] === maxVal){
console.log(j, `${
maxVal}次`)
}
}
}
getMaxAmount(arr3) // 3 2次 6 2次 7 2次
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
Redis缓存一致问题(延迟双删)
