Brief Notes: Create An Array of Unique Elements in JavaScript.

This article is about creating an array of unique elements using the JavaScript Set object. Before I go straight to the technique, I would like to explain why it is specific to arrays of items that are primitive.

Example JavaScript primitive types are string, number, bigint, boolean, undefined, symbol, and null. Because objects are stored as references in JavaScript, two objects with similar key-value pairs but assigned to different variables are not the same.

const object1 = { name: 'terungwa' }
const object2 = { name: 'terungwa' }
// object1 === object2 is false

const primitive1 = 1
const primitive2 = 1
//primitive1 === primitive2 is true

Another important property of a primitive type is that it is immutable. By immutable we mean that a primitive value can be replaced but cannot be directly altered. An example that illustrates this can be seen in the snippet below.

let primitive = "terungwa";
console.log(primitive);               
// logs out terungwa
primitive.toUpperCase();
console.log(primitive);  
// logs out terungwa while we were expecting TERUNGWA

Based on how JavaScript values (reference type or primitive type) behave, we can see that adding two similar values to a Set will produce different results depending on the type. If we add two similar objects assigned to two different variables to a Set, they are stored separately in the set.

const object = {}
const object1 = {}
const mySet = new Set();
mySet.add(object);
mySet.add(object1);
console.log(mySet.size);
// logs 2

If we do the same with two similar values that are primitive, the JavaScript Set object ignores one of the variables.

const primitive1 = 1;
const primitive2 = 1;
const mySet = new Set();
mySet.add(primitive1);
mySet.add(primitive2);
console.log(mySet.size);
// logs 1

Now back to the core of this article, how do we ensure that an array of items that are primitive have no duplicates. We illustrate with the code snippet below:

const arrayOfPrimitives = ['terungwa', 'terungwa', 1, 1, 3, 'kombol']
const arrayOfUniquePrimitives = new Set(arrayOfPrimitives);
console.log(Array.from(arrayOfUniquePrimitives))
// logs [ 'terungwa', 1, 3, 'kombol' ]