Get Unique Values From Array In JavaScript

Paulund
1 min readSep 24, 2022

--

In this tutorial, you will learn how to get the unique values from inside an array in JavaScript.

There are a few ways this can be done some of the most common ways are to use JavaScript array functions such as map and filter. But as of ES6 a object called Set was introduced which allows you to store a collection of the unique values of any type.

This can be used in line with the spread operator to return the values of an array.

const unique = [...new Set(array)]

For example if you have the following array.

const array = [
'this',
'is',
'an',
'array',
'of',
'text',
'this',
'is',
'an',
'array',
'of',
'text',
];

You can use the Set object to return the unique values of the array.

export const unique = (values: Array<string>): Array<string> => [...new Set(values)]

This will return

console.log(array) 
// ['this', 'is', 'an', 'array', 'of', 'text']

Unique Function

Originally published at https://paulund.co.uk.

--

--

Paulund
Paulund

No responses yet