js implements de-duplication according to the attribute value in the object array (only one of the same attribute value is kept)

Object array arr, de-duplicate according to the id attribute, only keep one of the same id value

    var arr = [
        {name: 'a', id: 1},
        {name: 'a', id: 2},
        {name: 'b', id: 2},
        {name: 'c', id: 4},
        {name: 'c', id: 6},
        {name: 'b', id: 6},
        {name: 'd', id: 7}];

    function deWeight(arr) {
        for (var i = 0; i < arr.length - 1; i++) {
            for (var j = i + 1; j < arr.length; j++) {
                if (arr[i].id == arr[j].id) {
                    arr.splice(j, 1);
                    //因为数组长度减小1,所以直接 j++ 会漏掉一个元素,所以要 j--
                    j--;
                }
            }
        }
        return arr;
    }

    // 调用
    var data = deWeight(arr);
    console.log(data);

 

js method to achieve array deduplication (using indexOf() method):  https://blog.csdn.net/qq_40015157/article/details/110795045 

Guess you like

Origin blog.csdn.net/qq_40015157/article/details/113601966