JS获取数组中成员出现最多次数的成员值及其出现的次数
function findNum (arr) {
let result = JSON.parse(JSON.stringify(arr)) || [];
let obj = {}
Array.from(new Set(result)).map(item => {
obj[item] = []
arr.map(a => {
if(a == item) {
obj[item].push(a)
}
})
obj[item] = obj[item].length || ''
})
//出现最多成员出现的次数
let maxIndex = Math.max.apply(Math, Object.values(obj) || []) || '';
//出现最多的成员值
let maxVal;
for(let key in obj) {
if(obj[key] == maxIndex) {
maxVal = key;
}
}
return { maxIndex, maxVal }
}
let arr = [1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 1]
let { maxIndex, maxVal } = findNum(arr)