Getting Unique Array Values in Javascript and Typescript

Chris Engelsma
2 min readAug 11, 2021

--

Photo by Donald Giannatti on Unsplash

Note: I will be using Typescript syntax for this tutorial

Suppose you have an array of strings and you want to get only the unique values from this array.

const array: string[] = [ 'Scooby', 'Dooby', 'Dooby', 'Doo' ];

The Good, The Bad, and The Ugly.

Approach One: The Ugly

The most-straightforward way might be to keep two arrays: the original array and the array intended for unique values, and only add over values into the unique array if we’ve confirmed that the value doesn’t already exist. We do this by using a nested for-loop:

const array: string[] = [ 'Scooby', 'Dooby', 'Dooby', 'Doo' ];
const uniques: string[] = [];
for (const value of array) {
let exists = false;
for (const unique of uniques) {
if (unique === value) {
exists = true;
break;
}
}
if (!exists) {
uniques.push(value);
}
}

While this technically works, it’s also a hot mess.

Approach Two: The Bad

We can improve upon the last approach by using the Array built-in method includes :

const array: string[] = [ 'Scooby', 'Dooby', 'Dooby', 'Doo' ];
const uniques: string[] = [];
for (const value of array) {
if (!uniques.includes(value)) { uniques.push(value); }
}retu

This dramatically reduces the code and is a huge improvement.

Approach Three: The Good

Let’s say you’re managing multiple arrays and want the ability to filter them at any time. We could take the previous solution, wrap it in a function, and invoke that function at any time (which is a totally valid solution). If we want to grow our programming prowess and turn it to 11, we can create a custom array filter.

function uniqueFilter(value, index, self) {
return self.indexOf(value) === index;
}
// ...const array: string[] = [ 'Scooby', 'Dooby', 'Dooby', 'Doo' ];const uniques: string[] = array.filter(uniqueFilter);

We now have a function uniquesOnly defined somewhere that we can pass as the parameter to the filter built-in function.

How it works

The filter function will pass in three parameters for us to use:

  • value (the current array value),
  • index (the current index), and
  • self (the array)

The filter will grab the first index of the passed-in value by invoking the indexOf function on the array. It then compares this discovered index value with the currently iterated index value.

In this case, it will resolve that the second ‘Dooby’ (at index 2) does not match up with the index of the first occurrence of ‘Dooby’ (at index 1), so it’s filtered out.

Conclusion

We can now use our uniqueFilter function and apply it to any filter where we want to extract a unique array.

Happy Coding!

--

--

Chris Engelsma
Chris Engelsma

Written by Chris Engelsma

Geophysicist, software engineer, and web developer. Hopefully if I throw enough spaghetti at the wall something sticks.

Responses (2)