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']
Originally published at https://paulund.co.uk.