美文网首页
封装reduce根据某个属性对数组对象去重

封装reduce根据某个属性对数组对象去重

作者: bryan_liu | 来源:发表于2022-04-24 09:40 被阅读0次
function duplicateRemovalArr (arr, key) {
    let hash = {};
    let result = arr.reduce((total, currentValue) => {
        if (!hash[currentValue[key]]) {
            hash[currentValue[key]]= true;
            total.push(currentValue);
        }
        return total;
    },[]);
    return result;
}

示例如下:

let arr = [{id:1,name:'小明'},{id:1,name:'小南'},{id:3,name:'小明'}]
根据对象属性name去重
duplicateRemovalArr (arr,'name')

执行结果如下:


执行结果.png

相关文章

网友评论

      本文标题:封装reduce根据某个属性对数组对象去重

      本文链接:https://www.haomeiwen.com/subject/asxtyrtx.html