JS查詢數組中出現次數最多的元素--通過reduce解決

const arrx = [1, 2, 3, 'x', 'y', 3, 6, 2, 1, 1, 'y', 'x', {a: 2}]
const resx = arrx.reduce((acc ,cur) => {
    cur in acc ? acc[cur]++ : acc[cur] = 1
    return acc
}, {})
console.log('resx', resx)

const _temp = {
    key: 0,
    value: 0
}
Object.keys(resx).map((item, index) => {
    if (resx[item] > _temp.value) {
        _temp.key = item
        _temp.value =  resx[item]
    }
})

console.log(_temp)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章