JavaScript Arrays Removing duplicate elements


From ES5.1 onwards, you can use the native method Array.prototype.filter to loop through an array and leave only entries that pass a given callback function.

In the following example, our callback checks if the given value occurs in the array. If it does, it is a duplicate and will not be copied to the resulting array.

var uniqueArray = ['a', 1, 'a', 2, '1', 1].filter(function(value, index, self) { 
  return self.indexOf(value) === index;
}); // returns ['a', 1, 2, '1']

If your environment supports ES6, you can also use the Set object. This object lets you store unique values of any type, whether primitive values or object references:

var uniqueArray = [... new Set(['a', 1, 'a', 2, '1', 1])];

See also the following anwsers on SO: