JavaScript: Sets vs. Arrays

JavaScript: Sets vs. Arrays

JavaScript: Sets vs. Arrays .Sets give JavaScript developers a new way to represent data. While Arraysremain the general-purpose workhorse of JavaScript applications, Setsare intended to represent a uniquecollection of values.

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 Arraysremain the general-purpose workhorse of JavaScript applications, Setsare intended to represent a uniquecollection 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.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Java vs. JavaScript: Know The Difference

Java vs. JavaScript: Know the Difference, Java vs. JavaScript: What's the Difference? Java vs. JavaScript: Major Similarities and Differences. pros and cons of JavaScript and Java.

Programming a Javascript Simon Game Tutorial

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

Understanding Memoization And Dynamic Programming in Javascript

In this Javascript tutorial I will explain what memoization is, how to use it, when you should use memoization, how to use memoization, what dynamic programming is, how to use memoization in dynamic programming. Memoization is a big complicated word that you may have never even heard before, but you may be surprised to know that you are most likely already using memoization without even realizing it.