javascript Map object vs Set object

Javascript

Javascript Problem Overview


JavaScript Map and Set objects are both iterable objects. Both store object by [key, value] pair. I want to know when to use what? Is there any preference one over another?

Javascript Solutions


Solution 1 - Javascript

Provided you are talking about the ES6 types, they aren't the same data structure even though the Set might be implemented with a Map.

Your definition of Map is right, but a Set is a collection of unique values, unlike an array which can have duplicates.

var array = [1, 2, 3, 3];

var set = new Set(array); // Will have [1, 2, 3]
assert(set.size, 3);

var map = new Map();
map.set('a', 1);
map.set('b', 2);
map.set('c', 3);
map.set('C', 3);
map.set('a', 4); // Has: a, 4; b, 2; c: 3, C: 3
assert(map.size, 4);

Solution 2 - Javascript

Summary:

  • Use a Set when your dataset needs to be composed of unique values
  • Use a Map when you have pairs of associated data. You map the keys to the values

Example Set:

There is a meeting with people coming from different organizations. Some people come from the same organization. We need to compose a list all the different organzations. For this we can use a set since we only want to include every organization once:

const organization = new Set();

organization.add('org1');
organization.add('org2');
organization.add('org3');
organization.add('org1');
organization.add('org3');
organization.add('org1');

for(let org of organization){
  console.log(org);
}

Example Map:

We have a pack of dogs and want to assign an age to each dog. We want to map the unique name of each dog to the age of the dog:

const dogs = new Map([['fluffy', 10], ['barkie', 13]]);

dogs.forEach((value, key) => console.log(key, value));

How is Map different from an Object?

An Object is also a collection of key value pairs and can fulfill often the same purpose as a Map can (which is creating key-value pairs). However, there are some key differences between a Map and an Object:

  • Map is built in Iterable, this allows it to use the for of loop or its implementation of the forEach() method which an plain JS Object cannot use.
  • Map has some nice built in methods on its prototype which makes working with it very nicely. Because al Objects inherit from Object.prototype is has access to more useful methods. For example, the size() method on Map returns the number of keys in the Map.

Solution 3 - Javascript

var obj = {};
obj.name= "Anand Deep Singh";
console.log(obj.name); //logs "Anand Deep Singh"

similarly in ES6, we can use regular object.

var map = new Map();
map.set("name","Anand Deep Singh");
console.log(map.get("name")); //logs "Anand Deep Singh"

But noticeable thing is a Map isn’t created with the literal object syntax, and that one uses set and get methods to store and access data.

It has a has method to check whether the key exists in the object or not, delete method to delete the object and clear method to clear the entire object.

Set is a unique list of values. It’s simply a unique list.

var set = new Set(["a", "a","e", "b", "c", "b", "b", "b", "d"]);
console.log(set); //logs Set {"a", "e", "b", "c", "d"}

A Set can’t be accessed like an array, and it provides the same methods as a Map.

Solution 4 - Javascript

There are two main data structures:

  • Objects: are used for storing keyed collections.
  • Arrays: are used for storing ordered collections.

But that’s not enough for real life. That’s why Map and Set also exist.

  • Map: is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

For instance:

let map = new Map();

map.set('1', 'str1');   // a string key
map.set(1, 'num1');     // a numeric key
map.set(true, 'bool1'); // a boolean key


let hamid = { name: "Hamid" };
// hamid is the key for the map
map.set(hamid, 123); // an object key
  • Set : is a special type collection – “set of values” (without keys), where each value may occur only once.

instance:

let set = new Set();

let hamid= { name: "Hamid" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };

// visits, some users come multiple times
set.add(hamid);
set.add(pete);
set.add(mary);
set.add(hamid);
set.add(mary);

// set keeps only unique values
alert( set.size ); // 3
 

https://javascript.info/map-set

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMd Nazmoon NoorView Question on Stackoverflow
Solution 1 - JavascriptDaniel A. WhiteView Answer on Stackoverflow
Solution 2 - JavascriptWillem van der VeenView Answer on Stackoverflow
Solution 3 - JavascriptAnand Deep SinghView Answer on Stackoverflow
Solution 4 - JavascriptHamid ShojaView Answer on Stackoverflow