Remove duplicate objects from an array using javascript

后端 未结 9 1878
野性不改
野性不改 2020-12-02 21:21

I am trying to figure out an efficient way to remove objects that are duplicates from an array and looking for the most efficient answer. I looked around the internet everyt

9条回答
  •  北海茫月
    2020-12-02 21:55

    Here is a solution that works for me.

    Helper functions:

    // sorts an array of objects according to one field
    // call like this: sortObjArray(myArray, "name" );
    // it will modify the input array
    sortObjArray = function(arr, field) {
        arr.sort(
            function compare(a,b) {
                if (a[field] < b[field])
                    return -1;
                if (a[field] > b[field])
                    return 1;
                return 0;
            }
        );
    }
    
    // call like this: uniqueDishes = removeDuplicatesFromObjArray(dishes, "dishName");
    // it will NOT modify the input array
    // input array MUST be sorted by the same field (asc or desc doesn't matter)
    removeDuplicatesFromObjArray = function(arr, field) {
        var u = [];
        arr.reduce(function (a, b) {
            if (a[field] !== b[field]) u.push(b);
            return b;
        }, []);
        return u;
    }
    

    and then simply call:

            sortObjArray(dishes, "name");
            dishes = removeDuplicatesFromObjArray(dishes, "name");
    

提交回复
热议问题