Remove duplicate objects from an array using javascript

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

    I use this function. its not doing any sorting, but produces result. Cant say about performance as never measure it.

    var unique = function(a){
        var seen = [], result = [];
        for(var len = a.length, i = len-1; i >= 0; i--){
            if(!seen[a[i]]){
                seen[a[i]] = true;
                result.push(a[i]);
            }
        }
        return result;
    }
    

    var ar = [1,2,3,1,1,1,1,1,"", "","","", "a", "b"]; console.log(unique(ar));// this will produce [1,2,3,"", "a", "b"] all unique elements.

提交回复
热议问题