Sunday, August 8, 2021

How to use – JavaScript Map Function

Must read

Javascript Map Function is one of the most used functions for array-related manipulations for each element of that array. This is done using callback functions. The callback function in the end then will be executed for each element of the array to do the manipulations.

In this tutorial, we will go through some examples of how to use the javascript map function for your better understanding.

Example One: Using Array.Map() on a simple array

If you want to add 10 to each element of the array provided below. You will use a for loop to go through each element and then add 10.

let simpleArray = [1, 3, 5, 9, 0, 10];
for (let j = 0; j < simpleArray.length; j++) {
	simpleArray[j] = simpleArray[j] + 10;

The output will be:

[11, 13, 15, 19, 10, 20]

Taking the same example above but with the Javascript Map function.

let simpleArray = [1, 3, 5, 9, 0, 10];
let UpdatedArray ={
	return element + 10;

The output will be the same

[11, 13, 15, 19, 10, 20]

Example Two: Using Array.Map() on a Array of Objects

If we have an array with objects of user with user’s name and their investments per year and we want to create a new array which will have a full-sentences like “John has Invested a total of 20K for this year“.

Let’s see how this can be done using Array.Map()

let arrayOfObjects = [
    {"name": "John", "investment":"20k"},
   {"name": "Amy", "investment":"40k"},
   {"name": "Bill", "investment":"10k"},
let updatedArray ={
	return + " has invested a total of " + element.investment + " this year";

The output will be:

["John has invested a total of 20k this year", "Amy has invested a total of 40k this year", "Bill has invested a total of 10k this year"

Example Three: Using Array.Map() with other array functions

Let’s take “Example One” above and extend it.

  1. We need to add 10 to each element.
  2. After adding 10 to each element we just want to get all the even numbers
let simpleArray = [1, 3, 5, 9, 0, 10];

let updatedArrayEvenElements = simpleArray
	return element + 10;
	return element % 2 === 0

The output will be:

[10, 20]

For understanding Array Filter function in javascript click here

Advantages of using javascript map function over for loop

  • As in the above examples we can see the original array will not be affected. In cases where we do not want to make a modification to the original array Array.Map() is very helpful.
  • As we can se we can write a cleaner code using array map function in javascript. As we know less code is better.
  • You can use other array functions with the javascript array map function extend your array manupulations, as we did in the Example Three
  • Asynchronous calls in for loop does not work well with for loops, whereas javascript map function is much effective model that can combine async / await and promises.

More articles


Please enter your comment!
Please enter your name here

Latest article