收集大佬们的写法
有个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) )
console. log ( getMaxAmount ( arr2) )
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) )
console. log ( getMaxAmount ( arr2) )
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)
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)