Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the Map prototype have a `.map()` function? [closed]

I see a lots posts asking about how to map(Array.prototype.map) a Map. Most of the solutions is do the Array.from(...) but what I want to know is why doesn't Map itself support .map()?

Maybe some performance issue or we don't have this kind use case?

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/map Maybe is definition of map is The map() method creates a new array with the results of calling a provided function on every element in the calling array. but for this we can have different definition for Map.prototype.map

like image 496
MichaelMao Avatar asked Jun 30 '26 10:06

MichaelMao


1 Answers

The Map is built in similar concept to the Object but not an Array.

From the docs:

The Map object holds key-value pairs and remembers the original insertion order of the keys.

So, you can notice that Object has no property order while Map has.

Did you notice, the Map has key value pair like:

[[ 1, 'one' ],[ 2, 'two' ]]

There are differences on Map vs Object you can look on the doc.

You can see this example to know why this is compared with Object:

const map = new Map([[3, 'three'], [2, 'two'], [2, 'four']]);
console.log(map); // returns {3 => "three", 2 => "four"} 

You found it that it's not like an array. But like an object. So, you can try what you try with Object. You cannot use the .map() directly with Object but you you'll need to use for...in, Object.keys, forEach, for...of, Object.entries...

Like this you'll need to use Map with:

for...of

let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);

for (let entry of iterable) {
  console.log(entry);
}
// [a, 1]
// [b, 2]
// [c, 3]

for (let [key, value] of iterable) {
  console.log(value);
}
// 1
// 2
// 3

forEach

const mapMap = function(map, mapFunction){

  const toReturn = [];
  map.forEach(function(value, key){ // be careful to the args order
    toReturn.push(mapFunction(value, key));
  })

  return toReturn;
}

Array.from

Array.from(p).map( ([key, value]) => value * value )

The examples are extracted from the following sources on which you may be interested to look in further:

Array vs Set vs Map

How to map a map

ES6 Map vs Object: What and When

like image 102
Bhojendra Rauniyar Avatar answered Jul 02 '26 23:07

Bhojendra Rauniyar