Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

How to implement Javascript map function

Javascript map function

The Javascript map function or method exists within all Array in Javascript, is one of the most used and popular High order functions and it inherits from Array.prototype.map(). The map() method returns a new array by applying a callback function on each item of an array. But map() method and Map object are completely different map() function is a method from Array and Maps is a data structure.

What is the Javascript map method?

The Javascript map method creates a new array by transforming elements of the source array to a new value by applying a callback on each item of the array. We may change the original array element from one data type to another like a number to a string, or string to a number, or increment or decrement its value to a new value in a new array.


Features of Javascript map function

Javascript array has lots of features and built-in methods which are ready to use, the map method is one of them. Here are some of the features of the Javascript map method.

  1. It transforms the elements of the source array and returns a new array by applying callback function on each item of an array.
  2. It is a higher-order function, and the return type is implicit, especially when we have one statement in the map function.
  3. The size of the new return array is the same as the original or source array.
  4. An index is optional, no need to add it if you don’t need it in a callback function.

Syntax of map function in Javascript

As we now know the map function applies a callback on each item of an array. Here is the basic syntax of the map method.

array.map(function(currentValue, index, arr), thisValue)

Where function is a callback function and it takes one to three parameters as follows.

Parameter nameDescription
elementThe element represents an individual element of an array at a moment.
indexIt is optional and it represents an index of an item in an array at a moment.
arrThe arr is an optional parameter, it represents the array, on which we invoke forEach method.
thisValueIs optional, no need if we use the arrow function. Value to use as this when executing the callback function.
Javascript map method callback parameter

Or we can use the arrow function, we don’t need this value in the arrow function.

// map using arrow function
array.map((element, index) => { ... })
array.map((element, index, array) => { ... })

//Using callback
array.map(callbackFn);
array.map(callbackFn, this)

//Inline
map(function(element) { ... })
map(function(element, index) { ... })
map(function(element, index, array){ ... })

In the map function, we have a callback function as an argument, we have to supply an array element, run that through a function (which can be used to perform certain operations on the supplied array – such as, for example, converting each array item value to upper case or some transformation ), and subsequently returns a new array once completed.


Javascript map function example

Let’s demonstrate a few examples of the Javascript map method, in a map function we need a function as an argument, and that function is applied to each array element to transform its value.

Javascript map with anonymous arrow function

Example first find the square of the number in an array by passing the arrow function as a callback function.

const numArrays = [2, 4, 6, 8, 10];
const squareNumArrays = numArrays.map(item => item * item);
console.log('Original array numArrays : ' + numArrays);
console.log('New return arrary squareNumArrays : ' + squareNumArrays)
Javascript map function example

Here in this example, we have used the arrow function as the callback, we don’t supply a Javascript map index, where an item is each element of an array is passed to the arrow function and multiple it with its own to get the square number.


Javascript map index example

Let us demonstrate the second example to convert a Javascript array object to a string. Where we used an optional index on the map function. Here we are looping through a Javascript map array of objects called cars, it contains a list of car names and prices. We are taking Javascript map index and converting array object element to string with serial number and car name and price as shown below.

Javascript map index example
Javascript map with index
<!DOCTYPE html>
<html>
<body>

    <h2>JavaScript map function with index</h2>
    <h4>Cars price</h4>
    <p id="mapValue"></p>

    <script>

     const cars = [
       { name: 'Tata Punch', price: 549000 },
       { name: 'Hyndai Venue', price: 69900 },
       { name: 'Hyundai Creta', price: 101600 },
       { name: 'Tata Nexon EV', price: 1424000 }
     ];

    const carPriceInfo = cars.map((car, index) => {
      return (`${index + 1}. Car name ${car.name} price : ₹${car.price}<br>`);
     }).join('');

    document.getElementById("mapValue").innerHTML = carPriceInfo;
  </script>
</body>
</html>

The array.join() method is an inbuilt function in JavaScript that is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ) so we’re using join to remove the delimiter comma.


Javascript map with join – convert map value to a string

In the previous example, we used a map with the join() method. In our second example, we do the same with more complexity of using replace function and applying the ternary condition, if true then use Javascript map with join function, otherwise return an empty string.

In this example, we will create an array of query params into a string by using both Javascript maps and the join method. The output of our example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript map function</h2>

<p id="mapValue"></p>

<script>
 function wheresSql(wheres) {
   return wheres.length ? 'WHERE ' + wheres.map((where) => {
     return where.field + ' ' + where.operator + ' \'' + 
      where.value.replace('\'', '\'\'') + '\''
   }).join(' and ') : '';
 }

 let wheres = [
     { field: "dated", operator: ">=", value: "2021-08-12" },
     { field: "dated", operator: "<=", value: "2021-12-12" },
     { field: "name", operator: "=", value: "edupala" }
 ];

 document.getElementById("mapValue").innerHTML = "Value  " + wheresSql(wheres);
</script>
</body>
</html>

Once, we got the combined string from the map and join function, we assign this value to the div element using innerHTML properties and we get this string below as output.

Value WHERE dated >= ‘2021-08-12’ and dated <= ‘2021-12-12’ and name = ‘edupala’


Javascript map with a callback function

In this example, instead of using the arrow function, we can use the callback function as we have seen in syntax, even the arrow functions are callback functions in map methods. Let’s use cars, and object to retrieve only the price value to a new array.

Javascript map callback function example
Javascript map callback function example screenshot

Now new prices array is an integer array containing a list of prices of the cars.


Javascript map array of objects

In this example, we’ll apply a map to an array of object employees. The employee’s array object contains the employee’s name and salary. Let’s add a Christmas bonus to an employee’s December salary by 500 and return a new array object from it.

Javascript map array of objects
Javascript map return array of object screenshot

Here in our map function, we create December salary as an array object and increment December salary with salary plus 500.


Javascript map reverse order example

We can chain the Array method on each other, sometime we might want to add the output of the filter method with the map method on the array, or some other array methods like sort or reverse.

const squareDescend = [1, 2, 3, 5, 6, 7, 8, 9, 10].map(item => item * item).reverse();

We have an array of integers, we apply a map function to find it square, and then we apply reverse at end of the map, in which we get a square number in decreasing order in new an array squareDescend. [100, 81, 64, 49, 36, 25, 9, 4, 1]

Example 2 of javascript map reverse on the array object

We’ll use the map function with the reverse function on our salary bonus array object.

const employees = [
    { name: 'Smith', salary: 4000 },
    { name: 'Ram', salary: 3500 },
    { name: 'Lee', salary: 3000 }
];

const salaryBonus = employees.map(employee => {
    const decemeberSalary = {};  //Output array object

    decemeberSalary.name = employee.name;
    decemeberSalary.salary = employee.salary + 500;

    return decemeberSalary;
}).reverse();

console.log(salaryBonus);

//Output
[{name: 'Lee', salary: 3500 },
 {name: 'Ram', salary: 4500 },
 {name: 'Smith', salary: 3500}
]

We already had covered the difference between forEach and the map method of the array, if you want to know then check our previous article on it.

Difference between map and forLoop

The map is a method from the Array.prototype, to iterate and apply a function on each element of the array to transform the array value. The for loop is a keyword and is used to iterate, we should know the range of the loop in advance, here we can use the continue and break keyword to terminate the loop in between.

But we can’t terminate map iteration in between, it will iterate on each element of an array, where we can not use a break and continue in the map method.

In the map function, the original array is optional to pass as an argument in the callback function, so if we didn’t, then there is no way to make errors on the original array. But in the for loop, we can access the original array using its index inside for loop block and the possibility of introducing an error.

Conclusion
We had covered the map function in detail, which is completely different from the Maps object. We’ll make a separate tutorial on the Maps object later. Use a map function, when we want to transform an array element and want to return a new array from transformation. Use forEach method, when we want to apply a callback function on each item of an array and don’t want to return any value from it.

Related Post

How to implement Javascript map function

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top