Notes

[ES2015] Set object

Edit on GitHub

JavaScript

Set

A Set is not an Array but it can behave like one. It’s a collection of unique values.

The Set object lets you store unique values of any type, whether primitive values or object references.

 1let showroom = new Set()
 2
 3let Prius = {make: 'Toyota', model: 'Prius 2017'},
 4    Civic = {make: 'Honda', model: 'Civic 2016'},
 5    A6 = { make: 'Audi', model: 'A6 Sedan 2017'}
 6
 7showroom.add(Prius)
 8showroom.add(Civic)
 9
10if (showroom.has(Prius)) console.log('Prius is in the showroom') // Prius is in the showroom
11if (showroom.has(Civic)) console.log('Civic is in the showroom') // Civic is in the showroom
12
13console.info('Showroom size:', showroom.size) // Showroom size: 2
14
15showroom.delete(Prius)
16console.info('Showroom size:', showroom.size) // Showroom size: 1
17
18// Create an Array [] from Set {}
19let arrayOfCars = Array.from(showroom)
20console.log(arrayOfCars) // [ { make: 'Toyota', model: 'Prius 2017' },                                           
21                         // { make: 'Audi', model: 'A6 Sedan 2017' } ]   
22
23// Create a Set {} from an existing Array []
24let newShowroom = new Set(arrayOfCars)
25console.info('newShowroom size: ', newShowroom.size) // newShowroom size: 2

Use cases:

Related