Как написать свой map js

If you know howArray.map() works, you can jump here directly.

What is Array.map in javascript?

A map is a built-in function of Arrays in javascript which helps us iterate over each individual element of the array and returns a brand new array.

Enter fullscreen mode

Exit fullscreen mode

First let us understand how map behaves,

For Example:

const sample = [1,2,3];
const mapResult = sample.map(function(val, index, array) {
    console.log('val :', val, 'index :', index, 'array :', array);
    return (val * 2);
});

Enter fullscreen mode

Exit fullscreen mode

The output of the above snippet will be:

So, we can conclude that, for each value of the array the function gets executed. And the function has access to 3 arguments:

  • The current element that is processed
  • Current element’s index
  • Entire Array

We are returningval*2 on every iteration and that gets stored inmapResult.
So,mapResult has [2,4,6] in it and this wont modify the original arraysample.

Thus, whatever that is returned by map during each iteration, will get stored inside a brand new array and the original array remains untouched.

Note: If nothing is returned from the function thenundefined gets stored in the output array.And this array’s length will be same as that of the array on which map is done.

If we did not return anything in our previous example then,

map will always return an array.So we don’t have to write an explicit return from an Array.map function which is why we use map most of the times to iterate through lists in React.

Lets create our own map method[mymap]

Step 1:

  • We will create a new method[mymap] which allows us to useArray.mymap()
  • In order to use Array.mymap() we have to havemymap()‘s definition in Array.prototype.
Array.prototype.mymap = function(){

}

Enter fullscreen mode

Exit fullscreen mode

Now we will be able to run[1,2,3].mymap(); which will returnundefined.

Step 2:

  • map is called with function as an argument inside it. (eg:[1,2].map(function(val, index, arr){})). So, ourmymap function should accept a function as an argument.
  • The function in the argument should be called for each value in the array with 3 arguments:
    • The current element
    • Current element’s index
    • Entire Array
  • this refers to the array on whichmymap is done. this is the array itself.
Array.prototype.mymap = function(callback) {
    for (let index = 0; index < this.length; index++) {
        callback(this[index], index, this);
    }
}

Enter fullscreen mode

Exit fullscreen mode

Step 3:

  • Finally, we output the result to a new array and return them.
Array.prototype.mymap = function(callback) {
    const resultArray = [];
    for (let index = 0; index < this.length; index++) {
        resultArray.push(callback(this[index], index, this));
    }
    return resultArray;
}

Enter fullscreen mode

Exit fullscreen mode

Output:

Thats it :) we have implemented our own map method.

Share if it helped you :)

Next step: Try using similar approach and create a custom map for objects.

This is an old question, but because the existing answers could be very dangerous, I wanted to leave this answer for future folks who might stumble in here…

The answers based on using an Object as a HashMap are broken and can cause extremely nasty consequences if you use anything other than a String as the key. The problem is that Object properties are coerced to Strings using the .toString method. This can lead to the following nastiness:

function MyObject(name) {
  this.name = name;
};
var key1 = new MyObject("one");
var key2 = new MyObject("two");

var map = {};
map[key1] = 1;
map[key2] = 2;

If you were expecting that Object would behave in the same way as a Java Map here, you would be rather miffed to discover that map only contains one entry with the String key [object Object]:

> JSON.stringify(map);
{"[object Object]": 2}

This is clearly not a replacement for Java’s HashMap. Bizarrely, given it’s age, Javascript does not currently have a general purpose map object. There is hope on the horizon, though: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map although a glance at the Browser Compatability table there will show that this isn’t ready to used in general purpose web apps yet.

In the meantime, the best you can do is:

  • Deliberately use Strings as keys. I.e. use explicit strings as keys rather than relying on the implicit .toString-ing of the keys you use.
  • Ensure that the objects you are using as keys have a well-defined .toString() method that suits your understanding of uniqueness for these objects.
  • If you cannot/don’t want to change the .toString of the key Objects, when storing and retrieving the entries, convert the objects to a string which represents your understanding of uniqueness. E.g. map[toUniqueString(key1)] = 1

Sometimes, though, that is not possible. If you want to map data based on, for example File objects, there is no reliable way to do this because the attributes that the File object exposes are not enough to ensure its uniqueness. (You may have two File objects that represent different files on disk, but there is no way to distinguish between them in JS in the browser). In these cases, unfortunately, all that you can do is refactor your code to eliminate the need for storing these in a may; perhaps, by using an array instead and referencing them exclusively by index.

Have you ever heard about maps in JavaScript? Maps are a new object type that was introduced in ES2015. In this tutorial, you will learn all you need to know about this lesser known object type. You will learn about what maps in JavaScript are, how they work and how to use them.

As a JavaScript developer you probably know JavaScript objects. Objects allow you to store data in the form of a key-value pair. Maps are very similar to JavaScript objects. When you want to store some data in maps, you store those data also in the form of a key-value pair.

Also just like with objects, you can add new keys and delete existing, and retrieve their values from maps. When you compare maps and objects, there are some differences you should know about. Let’s take a look at those differences before moving further.

Maps vs Objects

One of the most important differences is that, when it comes to maps in JavaScript, you can use any data type to create keys. You can use even objects or functions. Objects will allow you to use only strings or a symbols. Another important difference is the order of keys-value pairs.

In maps, keys are ordered based on the order you’ve added them to the map. If you iterate over a map, you will get its keys in the same order in which you’ve created them. In case of objects, this is true since ES2015 and only for JavaScript engines that support this specification. Before ES2015, keys in objects were not ordered.

Another difference is how easy it is to get the size of a map. Like set, every map has a size property that says how many key-value pairs it contains. With objects, you would have to use keys() or values() to get an array of keys or values. Then, use length to get the length of this array to finally get the size of an object.

Another nice thing is that maps, like array, are iterable. You don’t have to get the keys or values first in order to iterate over them. You can do it right away. For example, you can use forEach() method, just like with array. You can also use for…of loop, just like with objects.

The last difference, that is good to know, is that maps are optimized for adding and removing of key-value pairs. Objects are not. This may not matter if you don’t need to manipulate with data often. If you do using maps may help you improve performance of your JavaScript code.

Creating maps in JavaScript

Maps are similar to objects. One thing that is different between them, among the things we just discussed, is how you create them. When you want to create a new object, there are multiple options to do that. For example, you can use new Object(), Object.create(), object literal or object constructor.

When you want to create a new map, there are two ways to do it. Well, theoretically. The first option to create new maps is by creating new empty Map object using new Map() and assigning it values later.

// Creating new map
let myMap = new Map()

From array to map

The second option is also about using new Map() to create new Map object. However, you can also pass in an array. To make this work, this array has to be structured in a specific way. It has to contain nested array for each key-value pair. Each array (key-value pair) has to contain two items, the key and the value.

// Create new map and assign it some values right away
const myMap = new Map([
  ['name',  'Jackie'],
  ['gender', 'female'],
  ['age', 23]
])

// Log the content of "myMap" map
console.log(myMap)
// Output:
// Map { 'name' => 'Jackie', 'gender' => 'female', 'age' => 23 }

From object to map

You can use the second option also with objects. You can take existing object and get all its entries with entries() method. The entries() method returns all entries in the same format as the array you saw in the previous example. So, you can pass the result of calling entries() method to the Map() object.

// Create new object
const myObj = {
  subject: 'Math',
  level: '1',
  difficulty: 'Medium'
}

// Create new map from "myObj"
const myMap = new Map(Object.entries(myObj))

// Log the content of "myMap" map
console.log(myMap)
// Outputs:
// Map { 'subject' => 'Math', 'level' => '1', 'difficulty' => 'Medium' }


// Or, a bit longer
// Create new object
const myObj = {
  subject: 'Math',
  level: '1',
  difficulty: 'Medium'
}

// Get all entries
const myObjEntries = Object.entries(myObj)

// Create new map from "myObjEntries"
const myMap = new Map(myObjEntries)

// Log the content of "myMap" map
console.log(myMap)
// Outputs:
// Map { 'subject' => 'Math', 'level' => '1', 'difficulty' => 'Medium' }

Adding values to maps

When you want to add values, key-value pairs, to an object there are two ways to do that. Well, three, if you count adding values during object initialization. The first is using do notation. The second is using square brackets. The second way, square brackets, works also with maps.

That said, adding values to maps using square brackets is not a good practice. The problem is that when you do this you will lose performance optimizations maps have. The right way to add values to maps is by using set() method. This method accepts two parameters. First is for the key and second for the value.

// Create new map
const myMap = new Map()

// Create simple function
function sayHi() {
  return 'Hello!'
}

// Add some values (key-value pairs) to "myMap"
myMap.set('name', 'James Reacher')
myMap.set('bio', { age: 35, height: 189, weight: 82 })
myMap.set(sayHi, 'Function as a key?')

// Log the content of "myMap"
console.log(myMap)
// Output:
// Map {
//   'name' => 'James Reacher',
//   'bio' => { age: 35, height: 189, weight: 82 },
//   [Function: sayHi] => 'Function as a key?'
// }

When you want to add multiple key-value pairs to a map you can do it only one at the time. One interesting thing is that maps support chaining. So, yes, you have to use set() method for every key-value pair you want to add. However, you can chain these methods so you don’t have to use the name of the map over and over again.

// Create new map
const myMap = new Map()

// Add some values using chaining
myMap.set('Language', 'JavaScript')
  .set('Author', 'Brendan Eich')
  .set('First appeared', '1995')

// Log the content of "myMap"
console.log(myMap)
// Output:
// Map {
//   'Language' => 'JavaScript',
//   'Author' => 'Brendan Eich',
//   'First appeared' => '1995'
// }

Removing values from maps

When you want to remove values from maps the process is simple. There is a method you have to use called delete(). This method accepts one parameter, the key of the key-value pair you want to remove. If the deletion is successful, the delete() method will return true. If the key doesn’t exist, it will return false.

One thing to remember about delete() method is that it works only with one key at the time. You can’t pass in multiple keys. If you try it the delete() method will remove only the first key. It will ignore the rest.

// Create new map
const myMap = new Map()

// Add some values to "myMap"
myMap.set('name', 'Joe')
myMap.set('age', 25)

// Log the content of "myMap"
console.log(myMap)
// Output:
// Map { 'name' => 'Joe', 'age' => 25 }

// Remove "name" from "myMap"
myMap.delete('name')

// Log the content of "myMap" again
console.log(myMap)
// Output:
// Map { 'age' => 25 }


// This will not work
// Create new map
const myMap = new Map()

// Add some values to "myMap"
myMap.set('name', 'Joe')
myMap.set('age', 25)

// Try to remove "name" and "age" at the same time
myMap.delete('name', 'age')

// Log the content of "myMap" again
// Hint: only the "name" will be removed
// because it was the first parameter
console.log(myMap)
// Output:
// Map { 'age' => 25 }

Removing all values from maps

Removing values with delete() method is handy when you want to remove just one or few values. If you want to remove all values in a map at once, there is a better and faster way to do it. Aside from overwriting the map, you can do this also with clear() method. This method doesn’t accept any parameters.

// Create new map
const myMap = new Map()

// Add some values to "myMap"
myMap.set('The Lean Startup', 'Eric Ries')
myMap.set('Measure What Matters', 'John Doerr')
myMap.set('The Startup Owner's Manual', 'Steve Blank')

// Log the content of "myMap"
console.log(myMap)
// Output:
// Map {
//   'The Lean Startup' => 'Eric Ries',
//   'Measure What Matters' => 'John Doerr',
//   "The Startup Owner's Manual" => 'Steve Blank'
// }

// Remove all values from "myMap"
myMap.clear()

// Log the content of "myMap"
console.log(myMap)
// Output:
// Map {}

Retrieving values from maps

Adding and removing values from maps is straightforward. You can say the same about retrieving them. When you want to retrieve a specific value from a map you can use get() method. This method accepts one parameter, a key that is associated with the value you want to retrieve.

If the key its value you want to retrieve exists, it will return the value. If it doesn’t exist it will return undefined.

// Create new map
const myMap = new Map()

// Add some values to "myMap"
myMap.set('front-end', 'React')
myMap.set('back-end', 'Node.js')
myMap.set('database', 'MongoDB')

// Get the value of "back-end" key
myMap.get('back-end')
// Output:
// 'Node.js'

// Try to get the value of non-existent key "cms"
myMap.get('cms')
// Output:
// undefined

Checking if value exists in map

In some sense, the get() method can also help you check if some key exists in a map. However, there is a method dedicated for this. This method is called has(). Similarly to get(), the has() method also accepts one parameter, the key you are looking for. If the key exists has() returns true. If not, it returns false.

// Create new map
const myMap = new Map()

// Add some values to "myMap"
myMap.set('language', 'English')

// Check if "myMap" has "language" key
myMap.get('language')
// Output:
// true

// Check if "myMap" has "compiler" key
myMap.get('compiler')
// Output:
// false

Getting the size of the map

In the “Maps vs Objects” we discussed that one of the benefits of maps is that it is easy to find out their size. This is true. Every Map object has its own size property. This property is analogous to the length property that exists on arrays. Using this size property will quickly tell you how many key-value pairs are there in a specific map.

// Create new map
const myMap = new Map()

// Log the size of "myMap"
console.log(myMap.size)
// Output:
// 0

// Add some values to "myMap"
myMap.set('Tony Stark', 'Iron Man')
  .set('Steve Rogers', 'Captain America')
  .set('Black Widow', 'Natasha Romanoff')
  .set('Bruce Banner', 'Hulk')

// Log the size of "myMap" again
console.log(myMap.size)
// Output:
// 4

Iterating over maps

You know how to add values to maps and how to remove them. You also know how to retrieve values, one by one. Question is, what if you want to retrieve all values from a map? There are four options you can choose from. These options are keys(), values(), entries() and forEach() methods.

Map.keys(), Map.values() and Map.entries()

The first three methods all return Iterator object hat contain specific data. The first method, keys(), returns an Iterator with keys, one key for each pair in the Map. The second method, values() Iterator with values, also one value for each pair in the Map. The third method entries() returns an iterable for all entries.

These entries are returned in the form of a [key, value]. When you use these three methods you can then iterate over the returned Iterator object with next() method and its value property. Every use of next() method, along with value, will return the next value in the iterator, next value, key or entry in the map.

// Create new map
const myMap = new Map()

// Add some values
myMap.set('First name', 'Joshua Doer')
myMap.set('Email', 'joshua@doer.io')
myMap.set('username', 'josh1234')


// Example no.1: Map.keys()
// Create iterator for keys
const myKeysIterator = myMap.keys()

// Log the first key
console.log(myKeysIterator.next().value)
// Output:
// 'First name'

// Log the second key
console.log(myKeysIterator.next().value)
// Output:
// 'Email'

// Log the third key
console.log(myKeysIterator.next().value)
// Output:
// 'username'


// Example no.2: Map.values()
// Create iterator for values
const myValuesIterator = myMap.values()

// Log the first value
console.log(myValuesIterator.next().value)
// Output:
// 'Joshua Doer'

// Log the second value
console.log(myValuesIterator.next().value)
// Output:
// 'joshua@doer.io'

// Log the third value
console.log(myValuesIterator.next().value)
// Output:
// 'josh1234'


// Example no.3: Map.entries()
// Create iterator for entries
const myEntriesIterator = myMap.entries()

// Log the first entry
console.log(myEntriesIterator.next().value)
// Output:
// [ 'First name', 'Joshua Doer' ]

// Log the second entry
console.log(myEntriesIterator.next().value)
// Output:
// [ 'Email', 'joshua@doer.io' ]

// Log the third entry
console.log(myEntriesIterator.next().value)
// Output:
// [ 'username', 'josh1234' ]

Maps, iterators and for…of loop

Using the next() and value will not be the best tool if you want to get all data from Iterator object at once. For this, a better option will be for...of loop. This loop allows you to iterate over an Iterator and get all data inside, without the need to use next() multiple times.

// Create new map
const myMap = new Map()

// Add some values
myMap.set('First name', 'Joshua Doer')
myMap.set('Email', 'joshua@doer.io')
myMap.set('username', 'josh1234')


// Create iterator for entries
// NOTE: this will work in the same way
// also for keys() and values()
const myEntriesIterator = myMap.entries()

// Loop over the iterate object "myEntriesIterator"
for (let iteratorItem of myEntriesIterator) {
  // Log each item in the iterator
  console.log(iteratorItem)
}
// Output:
// [ 'First name', 'Joshua Doer' ]
// [ 'Email', 'joshua@doer.io' ]
// [ 'username', 'josh1234' ]

Map.forEach()

The forEach() method is a bit different. It doesn’t return Iterator object like keys(), values() and entries() and lets you iterate over those values manually. Instead, forEach() iterates over the map directly It also automatically iterates over all key-value pairs.

When it iterates over the pairs it executes a callback function for each of them. This callback function accepts three parameters. All these parameters are optional. These parameters are value, key and map. The value allows you to access current value in each iteration.

The key allows you to access current key in the iteration. The last one, the map, allows you to access the whole map you are iterating over.

// Create new map
const myMap = new Map()

// Add some values
myMap.set('title', 'JavaScript: The Definitive Guide')
myMap.set('author', 'David Flanagan')
myMap.set('publisher', 'O'Reilly Media')

// Loop over "myMap" map directly
myMap.forEach((value, key) => {
  // Log key and value in the map
  console.log(`${key}: ${value}`)
})
// Output:
// 'title: JavaScript: The Definitive Guide'
// 'author: David Flanagan'
// "publisher: O'Reilly Media"

From maps to objects

You know that you can create maps from objects. You can also do the opposite. You can take existing map and use it to create new object. This can be done with fromEntries() method. In the beginning, you used entries() method to create an array from entries that exist inside an object.

The fromEntries() method does the opposite thing. It takes an array, in the form of [key, value], and transforms it into an object. The entries() method that exists on map will help you transform any map into an array you need. You can then use that array with fromEntries() method to create new object.

// Create new map
const myMap = new Map()

// Add some values
myMap.set('spanish', 'Buenos dias')
myMap.set('french', 'Bonjour')
myMap.set('russian', 'Доброе утро')

// Transform the map into an array
const myTransformedMap = myMap.entries()

// Create new object from transformed map
const myObj = Object.fromEntries(myTransformedMap)

// Log the content of "myObj"
console.log(myObj)
// Output:
// {
//   spanish: 'Buenos dias',
//   french: 'Bonjour',
//   russian: 'Доброе утро'
// }

Conclusion: Introduction to maps in JavaScript

Maps are one of the lesser known, and less frequently used, object types in JavaScript. I hope this tutorial helped you learn what maps in JavaScript are, how they work and how to use them. I also hope it helped you distinguish when they can be a better choice than objects.

If you liked this article, please subscribe so you don’t miss any future post.

If you’d like to support me and this blog, you can become a patron, or you can buy me a coffee 🙂

Buy Me A Coffee

Patreon Become a Patron

PayPal icon
Donate via Paypal

It’s a well-established truth of the universe that JavaScript’s Array.prototype.map() is one of the best parts of the language, allowing us to write cleaner, simpler code to manipulate array values, instead of using something like forEach().

For example, let’s say we want to create a copy of an array with values that are tripled.

The Uncool Way

That works, but it’s rough around the edges. We need to declare an empty someTripledNumz array above, and then go through the process of tripling everything. But with .map(), things look better:

The Cool Way

What if we want to map() over the values of an object?

As it stands, you can’t. There’s no .map() method that exists on any object for us to use out of the box. But, thanks to prototypal inheritance, JavaScript provides a way to make that happen. We’re gonna try it out, so that afterward, we’ll be able to do something like this:

Let’s Map() Over an Object

First, let’s add an empty .map() method to the Object prototype. That method will accept a single argument: the callback method we’d like to fire on each of the values.

Next up, let’s pull all of our values out of the object we we’d like to map (it’ll be available within the this object), and actually map() over them like any other array, firing our function on each item.

Notice that when we fire that method, we’re also passing in the index and the original object itself as parameters. This is to keep our method as close to the actual specification as reasonably possible.

Once we have those manipulated values, we can piece our object back together with the appropriate keys.

We did it! But if you’re like me, you’re hungry for more. So, let’s:

Sidebar: It was really difficult to commit to using that meme. So overused. So 2013. But I’m choosing to submit to its applicability for this post. Now, we continue:

Let’s Map() Over a String()

This one’s a bit simpler than our Object map. Turn the target string into an array, map() over it as per usual, and turn it back into a string:

Then, we can do something like this:

Let’s Map() Over a Set()

Since it’s array-like, mapping over a Set is also relatively straightforward. Make it into an array, do the things, turn it back into a set. Thanks to the syntax of modern JavaScript, it looks pretty clean.

Let’s Map() Over a Map

This is where things get a wee bit nuttier. As we did before, the first thing we want to do in performing a map() on a Map() is get our target Map as an array. Take note of the format of this new array. Each item in that array is stored as an array itself, with the first item being the key, and the second being the value:

So, our prototype method beings like this:

And then, we’ll map over each item, handing if off to our callback method to do its thing.

And finally, piece that sucker back together by creating a new Map and adding values it it from our newMapAsArray.

Let’s try it out. If you weren’t aware, the keys or values don’t have to be of a particular type — objects, numbers, functions, etc. So, map() with responsibility.

Try the Package

Since what I wrote here includes a lot of functional, possibly useful code, I wrapped it all up into a package, ready for consumption. You can check it out here, and/or dive right in with npm install map-everything.

Code with Caution

Most of this was born out of “wouldn’t it be cool, if” within my brain. So, before shipping anything to production, be very intentional about what you’re manipulating, or deciding if it’s even worth adding these methods to all of these prototypes. All that said, this sure was fun! Thanks for mapping with me.

The Map object allows us to create collections of key-value pairs in JavaScript. Keys in the Map are unique and appear in the original insertion order. You can store any objects and primitives as keys and values.

Objects vs. Maps

The Map object was introduced in ES6 along with the Set object. It is similar to a JavaScript object used for storing key-value data. However, there are some important differences:

  1. The Map keys can be of any type and are not limited to strings and symbols.
  2. A Map object provides a property to get the size of the collection.
  3. A Map does not contain any keys by default. It only contains what is explicitly put into it.

Create a new Map object

You can use the Map() constructor to create an empty map:

const items = new Map()

You can also pass an iterable object, such as an array, to the Map constructor to initialize a map with values:

const items = new Map([
  ['🦅', 'Eagle'],
  ['🐶', 'Dog'],
  ['🐹', 'Hamster']
])

console.log(items)
// Map(3) { '🦅' => 'Eagle', '🐶' => 'Dog', '🐹' => 'Hamster' }

Alternatively, you can also initialize a map with values from a JavaScript object:

const user = { name: 'John Doe', age: 30 }

const map = new Map(Object.entries(user))
console.log(map)

// Map(2) {
//     'name' => 'John Doe',
//     'age' => 30
// }

Add elements to a Map

You can use the set() method to add elements to a Map object:

const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')
items.set('🚄', 'Train')
items.set(45, 'Number')
items.set(true, 'Boolean')

The set() method is chainable, which means you can combine multiple set() calls together, as shown below:

const user = new Map()

user.set('name', 'Atta').set('age', 34)

console.log(user)
// Map(2) { 'name' => 'Atta', 'age' => 34 }

Since the Map keys are unique, calling set() more than once with the same key won’t add multiple key-value pairs. Instead, the value part is replaced with the newest value, as shown below:

const animals = new Map()

animals.set('🐺', 'Wolf')
animals.set('🐺', 'Wolf Face')

console.log(animals) // Map(1) {"🐺" => "Wolf Face"}

Add objects to a Map

Since the Map object allows us to store any data type as a key or value, we can store complex objects like object literals, arrays, and even functions as keys and values:

const props = {
  browser: 'Chrome',
  os: 'Ubuntu 19.04'
}

const hamburger = () => '🍔'

const things = new Map()

things.set('birds', ['🦉', '🦅'])
things.set('user', { name: 'John Doe', planet: 'Earth' })
things.set(props, 59)
things.set(hamburger, 'What is the food?')

things.get(props) // 59
things.get(hamburger) // What is the food?

Get an element from a Map

You can use the get() method to get elements from a Map object:

const user = { name: 'Atta', age: 30 }

const items = new Map()
items.set('user', user)
items.set('rank', 12)

console.log(items.get('rank')) // 12
console.log(items.get('user')) // { name: 'Atta', age: 30 }

Check if an element exists in a Map

To check if an element exists in the Map object, you can use the has() method:

const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')

console.log(items.has('🐶')) // true
console.log(items.has('🐺')) // false

Get the number of elements in a Map

The Map object provides the size property to get the number of elements in the collection:

const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')

console.log(items.size) // 2

Delete an element from a Map

To remove an element from the Map object, you can use the delete() method:

const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')

console.log(items.delete('🐶')) // true
console.log(items.delete('🐶')) // false -> already removed
console.log(items.delete('🚄')) // false -> Not found

Delete all elements in a Map

To delete all entries in the Map object, you can use the clear() method:

const items = new Map()
items.set('🐶', 'Dog')
items.set('🦅', 'Eagle')

items.clear()

console.log(items.size) // 0

Iterate over Map keys

You can use the keys() method to get all keys in the Map object. It returns a new iterator object containing the keys of all elements in the map.

The following example demonstrates how you can use the keys() method and for...of loop to iterate over the Map object keys:

let john = { name: 'John Doe' },
  alex = { name: 'Alex' },
  pretti = { name: 'Pretti' }

const team = new Map([
  [john, 'Manager'],
  [alex, 'Lead'],
  [pretti, 'Developer']
])

for (const user of team.keys()) {
  console.log(user)
}

// { name: 'John Doe' }
// { name: 'Alex' }
// { name: 'Pretti' }

Iterate over Map values

The Map object provides the values() method to get an iterator object containing values for all the elements in the map:

let john = { name: 'John Doe' },
  alex = { name: 'Alex' },
  pretti = { name: 'Pretti' }

const team = new Map([
  [john, 'Manager'],
  [alex, 'Lead'],
  [pretti, 'Developer']
])

for (const role of team.values()) {
  console.log(role)
}

// Manager
// Lead
// Developer

Iterate over Map elements

You can use the for...of loop to iterate over all key-value pairs in the Map object. Since the Map remembers the original insertion order of the keys, the key-value pairs are returned in the same order as they were inserted:

const foods = new Map([
  ['🍌', 'Banana'],
  ['🍕', 'Pizza'],
  ['🥒', 'Cucumber'],
  ['🌽', 'Maize']
])

for (const [key, value] of foods) {
  console.log(`${key}: ${value}`)
}

// 🍌: Banana
// 🍕: Pizza
// 🥒: Cucumber
// 🌽: Maize

Alternatively, you can also use the forEach() method to iterate over all elements:

foods.forEach((value, key) => {
  console.log(`${key}: ${value}`)
})

// 🍌: Banana
// 🍕: Pizza
// 🥒: Cucumber
// 🌽: Maize

The Map object also has the entries() method that returns an iterable for entries [key, value]:

for (const [key, value] of foods.entries()) {
  console.log(`${key}: ${value}`)
}

You can call the next() method on the iterable returned by the entries() method to traverse the key-value pairs one by one:

const entries = foods.entries()

console.log(entries.next()) // {value: ["🍌", "Banana"], done: false}

Convert a Map to an array

You can convert a Map object to a two-dimensional array using the Array.from() method:

const foods = new Map([
  ['🍌', 'Banana'],
  ['🍕', 'Pizza'],
  ['🥒', 'Cucumber'],
  ['🌽', 'Maize']
])

const arr = Array.from(foods)
console.log(arr)

// [
//     [ '🍌', 'Banana' ],
//     [ '🍕', 'Pizza' ],
//     [ '🥒', 'Cucumber' ],
//     [ '🌽', 'Maize' ]
// ]

Alternatively, you can use the spread operator (...) to convert a Map object to an array:

const arr = [...foods]
console.log(arr)

// [
//     [ '🍌', 'Banana' ],
//     [ '🍕', 'Pizza' ],
//     [ '🥒', 'Cucumber' ],
//     [ '🌽', 'Maize' ]
// ]

✌️ Like this article? Follow me on
Twitter
and LinkedIn.
You can also subscribe to
RSS Feed.

Понравилась статья? Поделить с друзьями:
  • Как написать свой bootloader
  • Как написать свой bios
  • Как написать свой api на python
  • Как написать свой ahk скрипт
  • Как написать своими словами резюме