25
loading...
This website collects cookies to deliver better user experience
const mySet = new Set();
mySet.add(1); // add item
mySet.add('a');
mySet.size; // 2
mySet.delete(1)
mySet.has(1); // false
mySet.clear(); // empties set
const arr = [1,2,3,4,4,5,6,7,7,7]
const unique = [...new Set(arr)]
// unique equals [1,2,3,4,5,6,7]
const myMap = new Map();
myMap.set('a', 1);
myMap.set('b', 2);
myMap.set('c', 3);
myMap.get('a'); // 1
myMap.set('a', 'ok');
myMap.get('a'); // 'ok'
myMap.size; // 3
myMap.delete('b'); // removes b key/value
myMap.clear() // empties map
'[object Object]'
and overwrite each other. Luckily with maps, that’s not a problem! Each object would function perfectly well as a unique key. And if you used the same object key with a new value, it would overwrite the original value, just like you’d expect. It’s not a super common scenario, but it’s a good trick to know.Object.keys
, values
, and entries
iterating functions as well. Which, sort of steals that thunder a bit. And to my knowledge, maps don’t have any iteration speed bonus. Which leads me to my last point.Map.delete
function is faster than the object delete
keyword, but there’s a catch. The Map.set
function is slower than the internal object’s set
method, so whatever bonus you get from faster deletes would get a huge chunk taken out by slower inserts. Also, certain browsers implement things differently, which means it’s not a consistent boost. In my, albeit limited, testing, I found objects were always faster, but not by much.set.has
is faster than array.includes
(that’s O(N) for arrays vs. O(1) for sets). Unfortunately, set.add
seems much slower than arr.push
. So, if a list were big enough where searching was costly, the process of creating the set in the first place would be so slow that any speed boosts from repeated searching would be lost. I think if you were searching hundreds or thousands of times on a list with a ton of items, then sets might be worth it.