Map in JavaScript | Code Underscored

0
131

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

Using the callback function, you can use the Array.map () method to move an array and change its elements. Then, the callback function will be called at each entry of the array.

Various strategies and methods are used to repeat data sets in JavaScript, from the conventional loop for a 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. Unlike mutation methods, which only change the array of readers, .map () is a non-mutated method that creates a new array.

Syntax map ()

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

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

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

  • Element – Usually required, and has the value of the current element
  • index – is optional, and is the array index of the current element
  • Array – is also optional, and it is the array object of which the element is a part.
  • This is – by default, it’s optional. The value to be provided for a function is its “it” value. If this parameter is left blank, the value “not set” will be used as the value for “it”.

Each array element calls the callback () function, and the map () method always provides the current element, the index of the current element, and the whole array object.

Within the callback function, this parameter will be used. Its value is not set by default. Here’s how to change this value to number 25:

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

arrVals.map(function(element, index, array)
console.log(this)
, 25);
Change the array values ​​to 25

Practical application of a map ()

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

  • The function of read array components
  • To convert a string to an array
  • List Processing Assistance in JavaScript & Libraries
  • Redesign of array objects

Call a function in any array item

One of the mapping arguments () is the callback function. In this case, the current value processed by the function is one of the parameters of the same function. This is a binding parameter. Using this argument, you can modify any item in the array and return it as a different member in your new array.

Here is an illustration:

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

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

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

The above code can be further 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);
Simple code for dual array items
Simple code for dual array items

If we were to demonstrate a call to a function in any array item without using .map () in the previous example, we would get the result that would look like this.

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 a loop for dual array items
Using for a loop for dual array items

The Array.map () method is often used to modify the elements, such as multiplying by a set number as in the code above or performing any other action required by your application.

Convert a string to an array

It is known that the prototype of the array is represented by map (). We will use it to turn a string into an array at this point. Basically, we are not working on the way to invent here a method for working with strings. Instead, we will use the unique.call () method.

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

You can provide arguments for the context to use and parameters for the arguments of the original function to .call ().

Here is an illustration:

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

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

console.log(resultName)
Convert a string to an array
Convert a string to an array

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

This is similar to the split () method of the string, except that any string character can be edited before returning in the array.

Use JavaScript libraries to process lists

.Map () is used in JavaScript libraries like React to process elements in a list. Typically, this requires JSX syntax. However, in this case, the .map () method is wrapped in JSX syntax.

Here is the 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, it is a stateless element that creates a div that contains a list. To repeat the array of names, the .map () is used to process the individual list elements. This component is displayed in the root DOM component using ReactDOM.

Redesign of array objects

Repeat the objects in the array using map (), which changes the contents 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 is 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);
Redesign of array objects
Redesign of array objects

Using parentheses and periods, we can modify any object in the array. This use case can process or centralize data before saving or analyzing 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' 
];

Suppose you have an array of objects, each of which represents students, as shown above. The only thing you need in the end is an array that contains only each student’s ID.

You can 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 student 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 student names with their ages
Join student names with their ages

Summary

This article covers the four different essential ways to use the JavaScript .map () method. The capability of .map () can be improved by combining it with other methods. It’s all about the Array.map () method.

Remember to use only the element parameter most of the time and ignore the rest of the callback code back.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here