Map in JavaScript

You may occasionally need to take an array and process its elements, resulting in a new array with updated elements. Instead of manually iterating over the array with a loop, you can use the built-in Array.map() method.

Using a callback function, you can use the Array.map() method to traverse an array and change its elements. The callback function will then be called on each entry of the array.

Various strategies and methods are used to iterate across datasets in JavaScript, from the conventional for loop to the forEach() method. The.map() function is widely used because it produces an array by applying a function to each item in the parent array. In contrast to mutating methods, which only change the calling array, .map() is a non-mutating method that creates a new array.

The map() syntax

Below is the generic syntax of the method, map()

arr.map(function(element, index, array){ }, this);

The following section defines some of the items in this syntax.

  • Element – is usually required, and it has the value of the current element
  • index – it is optional, and it is the current element’s array index
  • array – it is also optional, and it is the array object that the element is part of.
  • this – by default, it is optional. The value that will be supplied to the function is its “this” value. If this parameter is left blank, the value “undefined” will be used as the value for “this.”

Each array element calls the callback function(), and the map() method always provides the current element, the current element’s index, and the entire array object.

Inside the callback function, this parameter will be used. Its value is undefined by default. Here’s how to modify this value to the number 25:

let arrVals = [2, 3, 5, 7]

arrVals.map(function(element, index, array){
console.log(this)
}, 25);
change array values to 25
change array values to 25

Practical application of map()

When working with arrays, this approach can be helpful in a variety of situations. In this article, you’ll learn how to use the .map() in JavaScript for four different purposes:

  • Call array elements’ function
  • To convert a string to an array
  • Aid to render a list in JavaScript libraries &
  • Array obj reformatting

Calling a Function on Each Array Item

One of the arguments to map() is a callback function. In this case, the current value processed by the function is one of the parameters of that function. It is an obligatory parameter. Using this argument, you can alter each item in an array and return it as a modified member of your new array.

Here’s an illustration:

let arrayVals = [7, 8, 9, 10, 40];

const resultArray = arrayVals.map(arrayItem => {
return arrayItem * 2
})

console.log(resultArray)
double array items
double array items

The code above can further be simplified as follows.

// create a function to use
const processVals = arrayItem => arrayItem * 2;

// we have an array
const arrayVals = [7, 8, 9, 10, 40];

// call the function we made. more readable
const resultArray = arrayVals.map(processVals);

console.log(resultArray);
simplified code to double array items
simplified code to double array items

If we were to illustrate calling a function on every array item without using .map() in the previous sample, we would end up with the result that will look as follows.

let arrayVals = [7, 8, 9, 10, 40];

for (let j = 0; j < arrayVals.length; j++){
arrayVals[j] = arrayVals[j] * 2;
}

console.log(arrayVals);
using for loop to double array items
using for loop to double array items

The Array.map() method is frequently used to modify the elements, such as multiplying by a specified number as in the code above or doing any other operations required by your application.

Converting a String to an Array

The array prototype is known to be represented by map(). We will use it to transform a string into an array in this phase. In essence, we’re not working on the way to come up with a method for working with strings here. Instead, we’ll utilize the method, unique.call().

In JavaScript, everything is an object, and methods are functions that are associated with these objects. You can use the context of one object on another with .call(). As a result, you’d be duplicating the .map() context from an array to a string.

Arguments for the context to be utilized and parameters for the original function’s arguments can be supplied to .call().

Here’s an illustration:

const varName = "Codeunderscored"
const map = Array.prototype.map

const resultName = map.call(varName, singleLetter => {
return singleLetter;
})

console.log(resultName)
Converting a String to an Array
Converting a String to an Array

We used the.map() context on a string and the function .map() from the code snippet above. The latter expects an argument.

It is similar to the string’s split() method, except that each string character can be edited before being returned in an array.

Using JavaScript Libraries to Render Lists

.map() is used by JavaScript libraries like React to render elements in a list. Usually, it requires JSX syntax. However, in this case, the.map() method is wrapped in JSX syntax.

Here’s a React component in action:

import React from "react";
import ReactDOM from "react-dom";

const fruits = ["apples", "melon", "mangoes", "bananas", "lemon"];

const fruitsList = () => (
  
  {fruitName}
  
  );

const rootElement = document.getElementById("root");
ReactDOM.render(, rootElement);

In React, this is a stateless component that renders a div containing a list. To iterate over the names array, the .map() is used to render the individual list elements. This component is rendered on the root DOM element using ReactDOM.

Reformatting Array Objects

Iterate through the objects in an array using map(), which modifies the content of each object and returns a new array in the same way as traditional arrays do. This change is made based on the results of the callback function.

Here’s an illustration:

const userInfo = [
{ name: 'ken', likes: 'swimming' },
{ name: 'ann', likes: 'adventure' },
{ name: 'bob', likes: 'gospel music' }
]

const userLikes = userInfo.map(itemVal => {
const additionalInfo = {};
  
additionalInfo[itemVal.name] = itemVal.likes;
additionalInfo.age = itemVal.name.length * 10;

return additionalInfo;
  
})

console.log(userLikes);
Reformatting Array Objects
Reformatting Array Objects

Using bracket and dot notation, we can change each object in the array. This use case can process or condense data before saving or parsing it in a front-end application.

Examples 1: Get the Id of the given student’s array

// What you have
var students = [
  { id: 34, name: 'Ann Thomon' },
  { id: 65, name: 'Bob Seers' },
  { id: 23, name: 'Hope Ozzel' },
  { id: 78, name: 'Wayne Brown' }
];

Assume you’ve been given an array of objects, each of which represents students, as shown above. The only thing you need in the end is an array holding merely each student’s id.

You might achieve this using.forEach(),.for(…of), or a simple.for() loop.

var studentIDS = students.map(function (student) {
  console.log(student.id)
});
Get the Id of the given student's array
Get the Id of the given student’s array

Examples 2: Combine Students Names with their ages

let studentsList = [
  {name : "Mike", age: "30"},
  { name : "Paul", age: "28"},
  { name : "Carrick", age: "65"}
];

let studentNameAge = studentsList.map(function(element){
    return `${element.name} ${element.age}`;
})

console.log(studentNameAge);
Join Students Names with their ages
Join Students Names with their ages

Conclusion

This article covered the four different crucial ways to use JavaScript’s .map() method. The capability of .map() can be enhanced by combining it with other methods. That’s all about the Array.map() method.

Remember that you’ll only use the element parameter most of the time and ignore the remainder of the callback code.

Similar Posts

Leave a Reply

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