Hold data by key, or as a set

INPUT · Slides

Set, a collection with no duplicates

01 / 05

The same thing gets mixed in

Gathering colours into an array, you can carelessly add the same colour twice. An array is a container that holds things lined up, so the same value goes in twice as it is.

Checking "is it already in there" with an if every time is a bother. Let us have the container do that for us.

02 / 05

A Set folds the same value into one

Write new Set() and you get a collection with no duplicates. You put things in with add(value), and the count is size, the same as Map.

However many times you add the same value, only one goes in. You do not have to check yourself.

const fruits = new Set();fruits.add("apple");fruits.add("orange");fruits.add("apple");console.log(fruits.size);

Result

2

03 / 05

Two ways to see the contents

The same as Map: hand a Set straight to console.log and the contents do not come out. The way this course shows things, you only get {}.

When you want to see the contents, these two.

  • spread it into an array with [...collection] (spread, that is)
  • take them one at a time with for...of
const fruits = new Set();fruits.add("apple");fruits.add("orange");console.log(fruits);console.log([...fruits]);for (const fruit of fruits) {  console.log(fruit);}

Result

{}
["apple", "orange"]
apple
orange

04 / 05

You cannot take things out by number

has(value) checks whether it is there, delete(value) removes one. So far the same feel as Map.

What differs is that you cannot take things out by number. Write collection[0] and you get undefined. It is not a container that gives the order meaning. If you want it by number, spread it into an array first.

const colors = new Set();colors.add("red");console.log(colors.has("red"));console.log(colors[0]);console.log([...colors][0]);

Result

true
undefined
red

05 / 05

Strip out the duplicates

This is where Set shines most. Write new Set(array) and you get a collection with the array's contents put straight in. Duplicates fold into one at that moment.

Turn it back into an array with [... ] and you have built an array with the duplicates stripped out in two lines. The work you wrote with for and if disappears. Right — let us try it.

const list = ["red", "blue", "red"];const colors = new Set(list);console.log([...colors]);console.log(colors.size);

Result

["red", "blue"]
2