Remove duplicate objects from an array using javascript

后端 未结 9 1904
野性不改
野性不改 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:35

    Basic sort-then-unique implementation, fiddle HERE:

    function unique(arr) {
        var comparer = function compareObject(a, b) {
            if (a.title == b.title) {
                if (a.artist < b.artist) {
                    return -1;
                } else if (a.artist > b.artist) {
                    return 1;
                } else {
                    return 0;
                }
            } else {
                if (a.title < b.title) {
                    return -1;
                } else {
                    return 1;
                }
            }
        }
    
        arr.sort(comparer);
        console.log("Sorted: " + JSON.stringify(arr));
        for (var i = 0; i < arr.length - 1; ++i) {
            if (comparer(arr[i], arr[i+1]) === 0) {
                arr.splice(i, 1);
                console.log("Splicing: " + JSON.stringify(arr));
            }
        }
        return arr;
    }
    

    It may or may not be the most efficient, and should be entirely scalable. I've added some console.logs so you can see it as it works.

    EDIT

    In the interest of saving on the space the function used, I did that for loop at the end, but it seems likely that didn't properly find only unique results (depsite it passing my simple jsfiddle test). Please try replacing my for loop with the following:

    var checker;
    var uniqueResults = [];
    for (var i = 0; i < arr.length; ++i) {
        if (!checker || comparer(checker, arr[i]) != 0) {
            checker = arr[i];
            uniqueResults.push(checker);
        }
    }
    return uniqueResults;
    

提交回复
热议问题