In this post, we'll learn how to:

  1. Check if every value in an array is unique
  2. Filter an array such that it only contains unique values
  3. Remove duplicate values from an array

Let's get started!

The callback function

We can write a simple function to help us. We'll use it as a callback for the Array.prototype.every() and Array.prototype.filter() methods.

The callback function for the every() and filter() methods accepts up to three arguments, in the following order:

  1. The current value in the array
  2. The index of the current value in the array
  3. The array itself

We need to check that the first index of the value is equal to the last index of the value. If so, the value is unique. Otherwise, it's a duplicate.

function isUnique(value, index, array) {
return array.indexOf(value) === array.lastIndexOf(value);
}

Check if every value is unique

The following is an array of fruits. The string 'apple' appears twice.

const fruits = [ 'apple', 'apple', 'banana', 'pear' ];

To check if every fruit is unique, we can pass our isUnique() function to the Array.prototype.every() method:

const fruitsAreUnique = fruits.every(isUnique);
console.log(fruitsAreUnique); // false

In this example, the every() method returns false. This is because there are two occurrences of the string 'apple', so not every fruit is unique.

Filter unique values

To remove fruits that appear more than once, we pass our isUnique() function to the Array.prototype.filter() method:

const uniqueFruits = fruits.filter(isUnique);
console.log(uniqueFruits); // [ 'banana', 'pear' ]

In this example, the filter() method removes both occurrences of the string 'apple' from the array. Because it appeared twice, it wasn't unique.

Remove duplicate values

We might just want to remove duplicate fruits from our array, such that we're still left with one of each fruit. We can easily do this with a Set.

We can pass our fruits array into the Set() constructor to create a Set—a collection of unique values—from the array. Then we can use the spread operator (...) to turn the Set back into an array.

const oneFruitEach = [ ...new Set(fruits) ];
console.log(oneFruitEach); // [ 'apple', 'banana', 'pear' ]

If you prefer, you can use the Array.from() method:

const oneFruitEach = Array.from(new Set(fruits));
console.log(oneFruitEach); // [ 'apple', 'banana', 'pear' ]

My friend Chris Ferdinandi has a helper function for this: dedupe.js.

Summary

  1. We can use the Array.prototype.every() method to check if every value in an array is unique.
  2. We can use the Array.prototype.filter() method to filter an array such that it only contains unique values.
  3. We can use a Set to remove duplicate values from an array.

View a demo on CodePen.