Organizational Research By

Surprising Reserch Topic

how to remove duplicate value from javascript array



asked Sep 13, 2013 in Java Interview Questions by rajesh
edited Sep 12, 2013
0 votes
25 views



Related Hot Questions

2 Answers

0 votes
The top answers have complexity of O(n²), but this can be done with just O(n) by using an object as a hash:
 
function getDistinctArray(arr) {
    var dups = {};
    return arr.filter(function(el) {
        var hash = el.valueOf();
        var isDup = dups[hash];
        dups[hash] = true;
        return !isDup;
    });
}
This will work for strings, numbers, and dates. If your array contains complex objects (ie, they have to be compared with ===), the above solution won't work. You can get an O(n) implementation for objects by setting a flag on the object itself:
 
function getDistinctObjArray(arr) {
    var distinctArr = arr.filter(function(el) {
        var isDup = el.inArray;
        el.inArray = true;
        return !isDup;
    });
    distinctArr.forEach(function(el) {
        delete el.inArray;
    });
    return distinctArr;
}
 
answered Sep 13, 2013 by rajesh
edited Sep 12, 2013
0 votes
Less code than you might think.
 
uniqueArray = myArray.filter(function(elem, pos) {
    return myArray.indexOf(elem) == pos;
})
or, using the 3rd ("this array") parameter of the filter callback:
 
uniqueArray = myArray.filter(function(elem, pos, self) {
    return self.indexOf(elem) == pos;
})
A word of warning: filter and indexOf are (relatively) recent additions to Javascript and don't work in ancient browsers. See here for details.
 
A more realistic version that tries to use hash lookups when possible:
 
uniq = function(ary) {
    var prim = {"boolean":{}, "number":{}, "string":{}}, obj = [];
 
    return ary.filter(function(x) {
        var t = typeof x;
        return (t in prim) ? 
            !prim[t][x] && (prim[t][x] = 1) :
            obj.indexOf(x) < 0 && obj.push(x);
    });
}
 
a = ["a", null, 12, window, window.undef1, "b", window, 12, "12", window.undef2, null]
console.log(uniq(a)) // ["a", null, 12, DOMWindow, undefined, "b", "12"]
answered Sep 13, 2013 by rajesh
edited Sep 12, 2013

...