Difference between Sets vs. Arrays in JavaScript

Difference between Sets vs. Arrays in JavaScript

Difference between Sets vs. Arrays in JavaScript

The Set object type was introduced in the 2015 ECMAScript specification and is ready to be used in Node.js and most browsers.

Sets are a lot like Arrays, but a bit different. This article explores these differences and explains when one should be used over another. Let’s take a look.

Sets, the New Kid on the Block

Sets are 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’s constructor to populate it. An iterable is just something that can be looped through, like an Array or a String.

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

Arrays, the Trusty Workhorse

Arrays are a major building block in most JavaScript applications, both old and new. If you have written JavaScript before, you are probably already 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 are similar but are meant to do slightly different things. A set is designed to represent a collection of unique items whereas an array is a bit more general purpose.

A good example of something that could be represented as a Set would be the courses that a college student takes in a single semester. They can take one or more courses, but they can’t take the same course more than once in a semester.

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

On the other hand, a collection of Pokemon cards would not be a good use case for a Set because it could contain duplicates. In this case, an Array would be a better way to represent the data.

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

Duplicates can be passed into a Set, but they won’t be preserved. Copy the following code into your browser console and see for yourself:

new Set([
  'Machop',
  'Diglett',
  'Charmeleon',
  'Machop',
  'Squirtle'
])
// Set(4) {"Machop", "Diglett", "Charmeleon", "Squirtle"}

The array passed into the set contained two Machops, but the set only retains one single copy. This behavior is subtle, but 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 an Array to represent the list of active categories, you need to take care to avoid duplicates. This could be done by checking that the list does not already contain the category being added.

The indexOf or includes methods could 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 used to find myself writing this kind of code all the time, but Sets can be used to handle this problem automatically. You can simply use the add method and the Set will always remain unique.

// Just add the category to the list
// No need to perform any checks in advance!
list.add(category)

Converting a Set Back to an Array

We already saw that an Array can be converted to a Set by passing the Array into the Set’s constructor, but how can a Set be converted to an Array?

One option is to call the Array from method statically:

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"]

The ES6 spread operator is another option:

const set = new Set(['Casablanca', 'The Wizard of Oz', 'Jaws'])
const arr = [...set]
console.log(arr)
// (3) ["Casablanca", "The Wizard of Oz", "Jaws"]

Sets do not support functional programming methods like map, filter, and reduce so it’s often convenient to convert them to Arrays for processing.

Using Sets to Remove Duplicates From an Array

Even if you prefer to hold your data in Arrays, Sets can still be helpful. A handy trick for removing duplicates from an Array is to convert it to a Set and then convert it back.

const cards = [
  'Machop',
  'Diglett',
  'Charmeleon',
  'Machop',
  'Squirtle'
]
const uniqueCards = [...new Set(cards)]
console.log(uniqueCards)
// (4) ["Machop", "Diglett", "Charmeleon", "Squirtle"]

How Do Sets Know Which Values Are Unique?

So far we’ve seen how Sets only hold unique values, but how exactly are unique values determined? Let’s play around a bit and find out.

First, let’s add the value 3 to a set twice:

new Set([1, 2, 3, 4, 3])
// Set(4) {1, 2, 3, 4}

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

new Set([1, 2, 3, 4, '3'])
// Set(5) {1, 2, 3, 4, "3"}

Interesting. The Set considers 3 to be different than '3'. What if we add matching arrays to a set?

new Set([['Jesse Pinkman'], ['Jesse Pinkman']])
// Set(4) {['Jesse Pinkman'], ['Jesse Pinkman']}

In this case, the Set retains two Arrays that have the same contents… What about objects?

new Set([{name: 'Ron Burgundy'}, {name: 'Ron Burgundy'}])
// Set(2) {{name: 'Ron Burgundy'}, {name: 'Ron Burgundy'}}

Object literals with matching keys and values are considered to be different as well

How Can All This Be Explained?

Sets use strict equality (===) to determine which values are unique. This explains why the set maintains a copy of both 3 (the number) and '3' (the string).

It also explains why Arrays and object literals that have the same contents are found to be unique. JavaScript compares objects by their reference, not their contents, and Arrays are just one particular kind of object.

Summary

Sets give JavaScript developers a new way to represent data. While Arrays remain the general-purpose workhorse of JavaScript applications, Sets are intended to represent a unique collection of values.

Converting between Sets and Arrays is easy. You can use a Set to ensure your data remains unique and then convert it to an Array to take advantage of functional methods like map, filter, and reduce.

Sets use strict equality to compare values and determine what is unique. Since JavaScript compares objects by reference, Arrays and object literals can be considered unique even when they contain the same contents.

This article focused on the conceptual side of Sets. You should now have a good idea of when a Set should be used, and when it would be better to stick to an Array.

Author Biography.

Lokesh Gupta
Lokesh Gupta

Overall 3+ years of experience as a Full Stack Developer with a demonstrated history of working in the information technology and services industry. I enjoy solving complex problems within budget and deadlines putting my skills on PHP, MySQL, Python, Codeigniter, Yii2, Laravel, AngularJS, ReactJS, NodeJS to best use. Through Knowledge of UML & visual modeling, application architecture design & business process modeling. Successfully delivered various projects, based on different technologies across the globe.

News & Blogs

6ec3fae84857a1f5dc59eebcc6c0775e.png

Building a carousel component in React using Hooks

One of the problems in web development today is the entangling of different layers. Not only do w...

2cda7519f703462a0eabd1c2e84e0001.jpg

Why shouldn’t you wait to jump onto Angular 2?

AngularJs is a JavaScript framework and is widely adopted framework in building Single Page Web A...

7ebe8f7d2be8625f6df997b5d45a86af.jpeg

How to Implement Real Time Notification Using S...

Real time web/versatile application are getting to be well known step by step. Administrations li...