js 对象数组去重并且保留最后的对象

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 去重
        var arr = [
            { name: '张三', id: 1, integral: 10 },
            { name: '李四', id: 2, integral: 20 },
            { name: '王五', id: 3, integral: 30 },
            { name: '赵六', id: 4, integral: 40 },
            { name: '王五', id: 3, integral: 10 },
            { name: '王五', id: 3, integral: 80 },
            { name: '赵六', id: 4, integral: 20 },
        ]
        console.log(arrayUnique2(arr, 'id'), 'name')

        /*
        reducer 函数接收4个参数:
            Accumulator (acc) (累计器)
            Current Value (cur) (当前值)
            Current Index (index) (当前索引)
            Source Array (srcArray) (源数组)
        */
        function arrayUnique2(arr, name) {
            var hash = {};
            return arr.reduce(function (acc, cru,index) {
                if (!hash[cru[name]]) {
                    hash[cru[name]] = {index:index}
                    acc.push(cru)
                }else{
                    acc.splice(hash[cru[name]]['index'],1,cru)
                }
                return acc;
            }, []);
        }
    </script>
</body>

</html>

  

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注