Introduction


While working with arrays, having to remove duplicate values is a common case. I introduce here 3 ways to do this.


Classic way


The idea here is to create an array, loop through the initial array and only insert in the new one the values that are not already here.

function uniqueArray1(arr) {
  const uniqueArray = [ ];
  for (let i=0; i < arr.length; i++) {
    if (uniqueArray.indexOf(arr[i]) === -1) {
      uniqueArray.push(arr[i]);
    }
  }
  return uniqueArray;
}


filter() way


We can also choose to use filter() method. The main advantage will be its concise syntax.


As a reminder, filter() is a method that creates and return a new array with all elements of the initial array that match a given callback. A simple use case of this method would be:

const animals = [‘cat’, ‘dog’, ‘fish’];
const filteredAnimals = animals.filter(animal => animal !== ‘dog’);
console.log(animals); // [‘cat’, ‘dog’, ‘fish’]
console.log(filteredAnimals); // [‘cat’, ‘fish’];


The callback can be called with 3 parameters: current value, current index, and initial array.

arr.filter(callback); // callback(currentValue, currentIndex, currentArray)


We can now define a function using filter() to remove duplicate values:

function uniqueArray2(arr) {
   return arr.filter((currentValue, currentIndex, currentArray) =>
    currentArray.indexOf(currentValue) === currentIndex);
}


Set way (ES2015)


The Set Object has been introduced in ES2015.


It helps us to store a set of elements, which are iterable in their insertion order. An interesting property of Set Object lies in the fact that a value can only be present once in a Set.


This way of removing duplicate values is even more concise than the previous one.

function uniqueArray3(arr) {
  return [...new Set(arr)];
}


We can also write it as follow:

function uniqueArray3(arr) {
 return Array.from(new Set(arr));
}


Conclusion


We have reviewed 3 ways of removing duplicate values of an array in JavaScript, a classic one and two more concise. The last one is only available in ES2015, so be careful with your app browsers requirements before using it.


I will analyze the performance of these 3 methods in a future post.