Can an Array Be Added to a Javascript Set?

Just like any other object in JavaScript, an array can be added to a Set using the Set.prototype.add() method, for example, like so:

// ES6+
const numbers = [1, 2, 3];
const set = new Set();

set.add(numbers);

console.log(set); // Set { [ 1, 2, 3 ] }

If you add the same reference of an array two or more times to a Set, it will only have one instance in the Set:

// ES6+
const numbers = [1, 2, 3];
const set = new Set();

set.add(numbers);
set.add(numbers);
set.add(numbers);

console.log(set); // Set { [ 1, 2, 3 ] }

However, if the reference of the array differs, even if the elements of the array are same, it is not considered equivalent:

// ES6+
const numbers = [1, 2, 3];
const set = new Set();

set.add(numbers);
set.add([1, 2, 3]);

console.log(set); // Set { [ 1, 2, 3 ], [ 1, 2, 3 ] }

This is because:

  1. Arrays are objects in JavaScript, and each new array has a reference to a different object in memory, and;
  2. Adding two arrays to a Set that are structurally equal (e.g. [] and []), does not guarantee uniqueness, as the Set uses the "Same-Value-Zero" algorithm, which compares objects by reference, and not by value.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.