JavaScript Arrays Removing duplicate elements

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.

5.1
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:

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

See also the following anwsers on SO:



Got any JavaScript Question?