© Russ Ferguson and Keith Cirkel 2017

Russ Ferguson and Keith Cirkel, JavaScript Recipes, 10.1007/978-1-4302-6107-0_10

10. Working with Sets

Russ Ferguson and Keith Cirkel2

(1)Ocean, New Jersey, USA

(2)London, UK

What Is the Difference Between a Set and an Array ?

Problem

In what situation would you use a set object over an array?

Solution

There are some similarities between the two objects. They can both hold on to data of different types. What separates a set is that the values all need to be unique.

The Code

Listing 10-1. Showing the Difference Between Sets and Arrays
var numberSet = new Set();    numberSet.add(1);    numberSet.add(2);    numberSet.add(3);    numberSet.add(3); //does not get added    console.log(numberSet.entries()); //returns SetIterator ...

Get JavaScript Recipes: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.