Here are today's visitors at the stall: Ana, Sam, Ana, Kim, Sam. You want to know two things: how many different people came, and how many times each person came. An array can hold the list, but an array does not remove the repeated names for you.
For jobs like this, JavaScript has two built-in containers, Map and Set. A Set stores a list of values with no repeats: the same value is kept only once. Put the visitor list in a Set and only Ana, Sam and Kim remain. A Map stores pairs of a key and a value. It is similar to an object, but its keys can be any type. A Map suits a count like "Ana: 2", which means Ana came twice.
Map: key and value pairs
The code below makes a Map, then adds to it, reads from it and replaces a value:
const users = new Map([
["ivan", 30],
["rio", 25],
]);
users.set("ani", 22);
console.log(users.get("ivan")); // 30
console.log(users.has("rio")); // true
console.log(users.size); // 3
users.set("ivan", 31);
console.log(users.get("ivan")); // 31
console.log(users.size); // 3
new Map([...])makes a new Map. Each small array like["ivan", 30]is one pair: its key is"ivan"and its value is30..set(key, value)adds a pair. If the key is already there, its old value is replaced..get(key)reads the value of that key. If the key isn't there, the result isundefined..has(key)checks whether that key is there. The answer istrueorfalse..delete(key)removes one pair..sizeis the number of pairs in the Map. Not.length.
Look at the last three lines. Setting a key that is already there does not add a new pair. A Map's keys are unique, so set("ivan", 31) replaces 30, and size stays 3.
The difference from a plain object is in the keys. An object's keys are always turned into text. A Map's keys can be any data type (numbers, text, even objects). The pairs in a Map also keep the order they were added in.
Set: a list with no repeats
The code below makes a Set from an array of five fruit names. Apple and mango are written twice:
const fruits = new Set(["apple", "mango", "apple", "orange", "mango"]);
console.log(fruits.size); // 3
fruits.add("apple"); // already there, nothing added
console.log(fruits.has("orange")); // true
new Set(array)makes a Set from an array and removes the repeats right away. Five items become three..add(value)adds one value. If that value is already there, the Set does not change..has,.deleteand.sizework the same way as on a Map.
So the difference between a Set and an array: an array can hold the same value many times, while a Set keeps it only once.
Drop the repeats from an array
You can use a Set to remove the repeats from an array:
const numbers = [1, 1, 2, 3, 3];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3]
The second line works in two steps:
new Set(numbers)makes a Set from that array, so the repeats are removed.[...]unpacks that Set and puts its values in a new array.
Those three dots are called spread, and the Spread & Rest lesson covers them in full. Array.from(new Set(numbers)) gives the same result. The original array does not change.
Count how often things appear with a Map
The code below counts how many times each colour appears. The key is the colour's name, and the value is that colour's count:
const colors = ["red", "blue", "red"];
const counts = new Map();
for (const c of colors) {
counts.set(c, (counts.get(c) || 0) + 1);
}
console.log(Object.fromEntries(counts)); // { red: 2, blue: 1 }
- The first time a colour appears, it is not in the Map yet, so
counts.get(c)givesundefined.|| 0replaces thatundefinedwith 0, then 1 is added to the 0. - When the same colour appears again,
counts.get(c)gives its old count, then 1 is added. Object.fromEntries(counts)turns the Map into a plain object. You need this, because the console in the exercises prints a Map as{}.
⚠️ A Map or a Set is not an array
.lengthon a Map or a Set. It givesundefined. Use.size.- Square brackets on a Map.
users["ivan"] = 30makes an ordinary property, not a pair inside the Map. So.getand.sizedon't see it. Use.setand.get. - Forgetting
|| 0when counting. The first count becomesundefined + 1, which givesNaN. - Returning a Set when an array was asked for. Turn the Set into an array first with
[...set]. JSON.stringifyon a Map.JSON.stringifyturns data into text (see the JSON lesson). For a Map, it gives"{}", so the content of the Map is lost. Turn the Map into a plain object first withObject.fromEntries(map).
TL;DR: A Map stores key and value pairs. .set() adds or replaces a pair, .get() reads a value, .has() checks for a key, .delete() removes a pair, and .size is the number of pairs. Its keys are unique and can be any type. A Set stores values without repeats, so [...new Set(array)] is the shortest way to remove the repeats from an array. To count how many times each word appears, use map.set(word, (map.get(word) || 0) + 1) for each word, then Object.fromEntries(map) when you need a plain object.
⚡ Map: key and value pairs
Write:
const users = new Map([
["ivan", 30],
["rio", 25],
]);
users.set("ani", 22);
users.set("ivan", 31);
console.log(users.size); // ?
Guess first: .set(key, value) puts one pair into the Map, and .size is the number of pairs. What is users.size?
3. The two starting pairs plus ani make three. A Map's keys are unique, so set("ivan", 31) only replaces 30. It does not add a new pair.
Meaning: new Map([...]) makes a Map, which stores key and value pairs. .set() adds a pair or replaces an old value, .get() reads a value, .has() checks whether a key is there, and .size is the number of pairs (not .length). Unlike an object, a Map's keys can be any type, and they keep the order they were added in.
⚡ Set: the same value only once
Write:
const fruits = new Set(["apple", "mango", "apple", "orange", "mango"]);
console.log(fruits.size); // 3
Meaning: A Set stores values without repeats. Apple and mango are written twice, so five items become three. .add() adds one value, but a value that is already there does not change the Set.
⚡ Drop the repeats from an array
Write:
const unique = [...new Set([1, 1, 2, 3, 3])];
// [1, 2, 3]
Meaning: new Set(...) makes a Set from that array, so the repeats are removed. Then [...] unpacks that Set and puts its values in a new array.