Javascript: Sets vs Arrays

Tram Ho

The Set object type was introduced in ECMAScript 2015 and is available for use in Node.js and most browsers. Sets is very similar to Arrays, but a bit different. This article explores these differences and explains when to use which.

Sets, the new kid in the Block

Set is a special object type available in ES6. You can create an empty set like this:

const characters = new Set()

Or, you can pass an iterable into the Set Set constructor to fill it. An iterable is just something that can be iterated through, like Arrays or Strings.

const characters = new Set(['Rod', 'Todd', 'Sherri', 'Terri'])

Arrays, the Trusty Workhorse

Arrays are a type of data type that is commonly used in most JavaScript applications, both old and new. If you’ve written JavaScript before, you’re probably familiar with them. You can create an array like this:

const characters = ['Rod', 'Todd', 'Sherri', 'Terri']

So What’s the Point?

These two data types look similar, but why would you have to create Set? Set is designed to represent a collection of unique elements while an array has a slightly more general purpose.

A good example of something that can be represented as a Set would be courses that a college student takes for a semester. They may take one or more subjects, but households may not study more than once in a semester.

const courses = new Set(['English', 'Science', 'Lego Robotics'])

On the other hand, a set of Pokemon cards will not be an example for Set because it may contain duplicate elements. In this example, using an array would be the best option for displaying data

const cards = [ 'Machop', 'Diglett', 'Charmeleon', 'Machop', 'Squirtle' ]

Duplicates can be passed into a set, but they will not be retained.

new Set([ 'Machop', 'Diglett', 'Charmeleon', 'Machop', 'Squirtle' ])

// Set(4) {"Machop", "Diglett", "Charmeleon", "Squirtle"}

The array passed into the Set consists of 2 ‘Machops’, but Set retains only one. This is very subtle and very useful.

How Can This Be Used?

Imagine that you are developing a blog and want to create a feature that allows visitors to search for posts that match one or more categories. Each category should only be applied once. If you are using Arrays to represent lists of active categories, you need to be careful to avoid duplication. This can be done by checking that the list does not yet contain the category being added. The IndexOf or Includes methods can be used to do this:

// If our list does not include the category

if (! list.includes (category)) {

// Then add the new category to the list

list.push (category)


I use this method often in my processing, but Set can be used to handle this problem automatically. You can simply use the add and Set methods to always retain unique elements.

let list = new Set ()

list.add (category)

Converting a Set Back to an Array

We saw an array can be converted to a Set by passing an array to the Set constructor.

But how to switch back?

One option is to call an array from a static method:

const set = new Set ([‘Casablanca’, ‘The Wizard of Oz’, ‘Jaws’])

const arr = Array.from (set)

console.log (arr)

// (3) [“Casablanca”, “The Wizard of Oz”, “Jaws”]

Or maybe using spread operator in ES6 is also an option:

const set = new Set ([‘Casablanca’, ‘The Wizard of Oz’, ‘Jaws’])

const arr = [… set]

console.log (arr)

// (3) [“Casablanca”, “The Wizard of Oz”, “Jaws”]

Set does not support functional programming methods like map, filter, reduce, so usually we have to convert them to arrays for processing.

How Do Sets Know Which Values ​​Are Unique?

We have seen that Set only retains unique values, but how exactly Set sets unique values. Let’s try an example.

First, add 1 part from 3 to 1 Set 2 times:

new Set ([1, 2, 3, 4, 3])

// Set (4) {1, 2, 3, 4}

The second number 3 disappears. This is consistent with what we’ve learned so far, but what if the last 3 is added as a string?

new Set ([1, 2, 3, 4, ‘3’])

// Set (5) {1, 2, 3, 4, “3”}

Interesting. Set considers 3 different from ‘3’. What happens if we add the same arrays into a set?

new Set ([[” Jesse Pinkman ‘], [‘ Jesse Pinkman ‘]]])

// Set (4) {[‘Jesse Pinkman’], [‘Jesse Pinkman’]}}

In this case, Set retains 2 arrays with the same content, what about Object?

new Set ([{name: ‘Ron Burgundy’}, {name: ‘Ron Burgundy’}])

// Set (2) {{name: ‘Ron Burgundy’}, {name: ‘Ron Burgundy’}}

Similarly, Objects with similar content are still considered different.

How Can All This Be Explained?

Sets use (===) to determine which value is unique. This explains why Set maintains a copy of both 3 (numbers) and ‘3’ (strings). It also explains why Arrays and text objects with the same content are found to be unique. JavaScript compares objects by their references, not their contents, and Arrays are just a specific type of object.


Set gives JavaScript developers a new way to represent data. Although Arrays are still a common feature of JavaScript applications, Set is intended to represent a unique set of values.

Switching between Ministries and Arrays is easy. You can use Set to make sure your data remains unique and then convert it into an Array to take advantage of methods like map, filter, reduce.

Set uses strict equations to compare values ​​and determine what is unique. Because JavaScript compares objects by reference, arrays and literal meanings of objects can be considered unique even if they contain the same content.

Set will be a great choice for basic data sets, there is only one data type that requires unique, no additional steps to eliminate duplication.


Chia sẻ bài viết ngay

Nguồn bài viết : Viblo