Completely removing duplicate items from an array

You could use Array#filter with Array#indexOf and Array#lastIndexOf and return only the values which share the same index.

var array = [1, 2, 3, 4, 4, 5, 5],
    result = array.filter(function (v, _, a) {
        return a.indexOf(v) === a.lastIndexOf(v);
    });

console.log(result);

Another approach by taking a Map and set the value to false, if a key has been seen before. Then filter the array by taking the value of the map.

var array = [1, 2, 3, 4, 4, 5, 5],
    result = array.filter(
        Map.prototype.get,
        array.reduce((m, v) => m.set(v, !m.has(v)), new Map)
    );

console.log(result);

Leave a Comment