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.
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);
Practical application of a map ()
- The function of read array components
- To convert a string to an array
- 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)
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);
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);
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.
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)
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.
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);
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) );
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);
Remember to use only the element parameter most of the time and ignore the rest of the callback code back.