Site icon Learn Web Development & Programming, Artificial Intelligence, WordPress, Shopify Articles

How to use map() in Javascript

map function in javascript

Introduction to JavaScript Array mapfunction or map()

The map function or map() in javascript is very helpful when you need to convert or modify the elements in an Array. See Below image code

It runs from left to right across the array to generate a new array, and for each item, some function is executed that is passed by args, and you must return a value for that function.

In this article, I would like to explain about the map() or map function, a JavaScript-related array function that I use a lot, and it’s very useful in different situations.

Also Read: How to Fix broken images automatically using jQuery

Let’s see an example below.

Suppose that you are receiving this data from your API as response:

So, you have an array of objects as below:

Let’s suppose we don’t need all above data, we need only an array with some objects like:

Probably, to fulfil this requirement , you may be thinking in something like:

Am I Right?

It isn’t wrong, and it works, but, there is a lot of steps, and, we can do it better!

Doing that way, you are:

  1. Instancing a new variable;
  2. Doing a for loop through the data Array, getting each index;
  3. Using this index to access the current element of the Array;
  4. Pushing the new object to the variable previously created;

The map() or map function provides an easy way to do the same task and with fewer steps!

Check below code snippet, how to write the same using map():

Let’s explain how every step work..

So, this also can be re-written to something like:

And if you’re familiar with ES6, you can re-write it to:

Output

Using any of the examples above, if you run a console.log(newData), you will receive

Conclusion

I hope you found this tutorial helpful for your project. I hope you guys enjoy The map() or map function in javascript and keep learning!. If you face – we are here to solve your problems.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Also Read: JavaScript Code to get Difference between two dates

Exit mobile version