TIL Using Set and Map
POSTED ON:
TAGS: javascript objects arrays
In ES6, there's Set
and Map
.
They sort of look just like arrays and objects.
What's the difference?
Let's start with the limitations with array
and object
:
- An
array
can store duplicate elements. - You cannot find the length of a
object
object
types don't have an insertion order.
What are Set and Map? #
Set
is an ordered collection of unique elements. It's shaped like an array
, but without duplicate elements.
Map
is a combination of an array
and object
. It has key-value pairs, but also remembers the insertion point, and it has a length
property.
Adding and removing elements #
SET
TYPE: #
Creating and deleting elements in a set
const set = new Set();
set.add('Batman');
set.add('Superman');
set.add('Wonderwoman');
set.add('Ironman');
set.delete('Ironman');
// set = {'Batman', 'Superman', 'Wonderwoman'}
set.size; // => 3
set.clear(); // empty the Set
// set = {}
Accessing the Elements in a set
const set = new Set();
set.add('Batman');
set.add('Superman');
set.add('Wonderwoman');
set.has('Ironman'); // false
set.has('Batman'); // true
console.log(set); // [object Set]
const data = set.values(); // this creates a SetIterator();
console.log(data.next().value); // Batman
console.log(data.next().value); // Superman
console.log(data.next().value); // Wonderwoman
Converting array
into a set
const myArray = [1, 2, 3];
const set = new Set(myArray);
MAP
TYPE: #
Creating and deleting elements in a map
const map = new Map();
map.set('Dark Knight', 'Batman');
map.set('The Kryptonian', 'Superman');
map.set('Amazonian', 'Wonderwoman');
map.set('Non-DC Hero', 'Ironman');
map.delete('Non-DC Hero');
// {"Dark Knight" => "Batman", "The Kryptonian" => "Superman", "Amazonian" => "Wonderwoman"}
map.size; // => 3
map.clear(); // empty the Map
// map => 0
Accessing the Elements in a map
const map = new Map();
map.set('Dark Knight', 'Batman');
map.set('The Kryptonian', 'Superman');
map.set('Amazonian', 'Wonderwoman');
map.get('Dark Knight'); // Batman
map.keys();
// {"Dark Knight", "The Kryptonian", "Amazonian"}
map.values();
// {"Batman", "Superman", "Wonderwoman"}
map.entries();
// {"Dark Knight" => "Batman", "The Kryptonian" => "Superman", "Amazonian" => "Wonderwoman"}
map.has('Dark Knight'); // true
map.has('Batman'); // false
Converting object
into a map
const myObject = {
'number': '1, 2, 3, 4, 5',
'letter' : 'abcdefg',
'symbols' : '@#$%^'
}
const myMap = newMap(Object.entries(myObject)); // object to map
const newObject = Object.fromEntries(myMap); // map to object
SOURCE:
Should you Stop using Objects and Arrays to Store Data? (Anurag Kanoria)
Related TILs
Tagged: javascript