We can use JavaScript to create a unique Array by converting the array to a set with the new Set() method and then back to an array with the Array.from() method.

var numbersArray = [0,7,7,7,0,2,3,1,1,4,5,6,7];

var convertToSet = new Set(numbersArray);

var convertBackToArray = Array.from(convertToSet);

console.log(convertBackToArray);

#Output:
[0, 7, 2, 3, 1, 4, 5, 6]

Look below to see a more compact version of this code.


When working with collections of data in JavaScript, the ability to get the unique values of your data is valuable.

To get the unique values of an array in JavaScript, the easiest way is by converting the array to a set with new Set() method and then back to an array with Array.from() method.

A set is an unordered collection of unique elements. On the other hand, arrays can contain duplicates.

Converting an array to a set creates a set with the same items as the array and returns a unique array.

Below is our example again of how to create a unique array with the new Set() method in JavaScript.

var numbersArray = [0,7,7,7,0,2,3,1,1,4,5,6,7];

var convertToSet = new Set(numbersArray);

var convertBackToArray = Array.from(convertToSet);

console.log(convertBackToArray);

#Output:
[0, 7, 2, 3, 1, 4, 5, 6]

We can put our code in a function, uniqueArray() to make it easy to reuse this code.

function uniqueArray(arr){
  return Array.from(new Set(arr));
};

And finally, let’s see this function in action using our same example.

function uniqueArray(arr){
  return Array.from(new Set(arr));
};

var numbersArray = [0,7,7,7,0,2,3,1,1,4,5,6,7];

console.log(uniqueArray(numbersArray));

#Output:
[0, 7, 2, 3, 1, 4, 5, 6]

Hopefully this article has been useful for you to learn how to use JavaScript to create a unique array.

Categorized in:

JavaScript,

Last Update: February 26, 2024