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.

javascript programming

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Learning JavaScript: Development Environments for JavaScript Programming

One of the nice things about learning JavaScript these days is that there is a plethora of choices for writing and running JavaScript code. In this article, I’m going to describe a few of these environments and show you the environment I’ll be using in this series of articles.

Learning JavaScript: Data Types and Variables

To paraphrase the title of an old computer science textbook, “Algorithms + Data = Programs.” The first step in learning a programming language such as JavaScript is to learn what types of data the language can work with. The second step is to learn how to store that data in variables. In this article I’ll discuss the different types of data you can work with in a JavaScript program and how to create and use variables to store and manipulate that data.

[ Professor JavaScript ]: Introduction

Professor JavaScript is a JavaScript online learning courses YouTube Channel. Students can learn how to develop codes with JavaScript from basic to advanced levels through the online courses in this YouTube channel.

From imperative to declarative JavaScript

In this post, I will explain why declarative code is better than imperative code. Then I will list some techniques to convert imperative JavaScript to a declarative one in common situations.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.