js数组reduce+hash+去重

小功能: 去除数组 arr 中重复出现过的元素

// 输入[1, 2, 4, 4, 3, 3, 1, 5, 3]
// 输出 [1, 2,3, 4,5]


function unique(arr){
   let hash= arr.reduce(((hash,a)=>{
        if(!hash[a]){
            hash[a]=true
        }
        return hash
    }),{})

    var retArr = []
    for (var key in hash) {
        if (hash[key]) {
            retArr.push(parseInt(key))
        }
    }
    return retArr


}
console.log(unique([1, 2, 4, 4, 3, 3, 1, 5, 3]))//=>[1,2,3,4,5]
小功能:找出数组 arr 中重复出现过的元素

输入[1, 2, 4, 4, 3, 3, 1, 5, 3],
输出 [1, 3, 4]


function duplicates(arr) {
    const hash = arr.reduce(function(ret, a) {
        if (hash[a]) {
            hash[a]++
        } else {
            hash[a] = 1
        }
        return hash
    }, {})
    let retArr = []
    for (const key in hash) {
        if (hash[key] > 1) {
            retArr.push(parseInt(key))
        }
    }
    return retArr
}
let arr = [1, 2, 4, 4, 3, 3, 1, 5, 3]
console.log(duplicates(arr)) // [1, 3, 4]

小功能: 统计数组 arr 中值各元素出现的次数

function countMap(arr) {
    return arr.reduce(function(hash, a) {
        if (!hash[a]) {
            hash[a]=1
        }else{
            hash[a]++
        }
        return hash
    }, {})
}
console.log(countMap([1, 2, 4, 4, 3, 3, 1, 5, 3])) //=>{ '1': 2, '2': 1, '3': 3, '4': 2, '5': 1 }
小功能: 统计数组 arr 中值等于 item 的元素出现的次数

如:
// 输入 [1, 2, 4, 4, 3, 4, 3], 4
// 输出 3


function count(arr, item) {
    return arr.reduce(function(sum, a) {
        if (a == item) {
            sum++
        }
        return sum
    }, 0)
}
console.log(count([1, 2, 4, 4, 3, 4, 3], 4))//=>3

发布了22 篇原创文章 · 获赞 0 · 访问量 2253

猜你喜欢

转载自blog.csdn.net/weixin_44156518/article/details/88354767