EN
JavaScript - get unique values in array
0 points
In this article, we would like to show you how to get unique values in a JavaScript array.
The below example presents the use of Set
object that lets us store unique values of any type.
The constructor of Set
takes an iterable object and the spread operator (...
) transforms the Set
object back into the array.
Runnable example:
xxxxxxxxxx
1
let array = ['A', 'B', 'B', 'B', 'C', 'C'];
2
3
let unique = [new Set(array)];
4
5
console.log(unique); // ['A', 'B', 'C']
Second example:
xxxxxxxxxx
1
let array = [1, 1, 'B', 'B', 'C', 'C'];
2
3
let unique = [new Set(array)];
4
5
console.log(unique); // [1, 'B', 'C']
Note:
Sets are a new object type introduced in ES6 (ES2015).