In this tutorial we will learn how to use Array Map in JavaScript with the help of different-different operations. Mainly it creates new array by applying on each element. So please have a look into. the below tutorial.
![Array map JavaScript](http://www.fluttertpoint.in/wp-content/uploads/2024/01/FlutterTPoint-Card-2-1-1024x576.png)
Why we user Array Map in JavaScript?
In JavaScript, the Array.prototype.map()
method is used to create a new array by applying a function to each element of an existing array. It does not modify the original array but instead returns a new array containing the results of applying the provided function to each element.
The syntax for map()
is as follows:
const newArray = array.map(callback(currentValue[, index[, array]]) {
// return element for newArray
}[, thisArg]);
array
: The original array on whichmap()
is called.callback
: A function that is called for each element in the array. It can take three parameters:currentValue
(the current element being processed),index
(the index of the current element), andarray
(the arraymap()
was called upon).thisArg
(optional): A value to use asthis
when executing the callback function.
Examples
Let’s go through some examples:
Doubling each element in an array
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function (number) {
return number * 2;
});
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
Mapping to a new object
const students = [
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 22 },
{ name: 'Charlie', age: 21 }
];
const studentNames = students.map(function (student) {
return student.name;
});
console.log(studentNames); // Output: ['Alice', 'Bob', 'Charlie']
Arrow function for conciseness
const originalArray = [1, 2, 3];
const newArray = originalArray.map(number => number * 10);
console.log(newArray); // Output: [10, 20, 30]
How to use index and array parameters?
const words = ['apple', 'banana', 'cherry'];
const modifiedWords = words.map(function (word, index, array) {
return `${word} is at index ${index} in the array [${array.join(', ')}]`;
});
console.log(modifiedWords);
// Output: ['apple is at index 0 in the array [apple, banana, cherry]',
// 'banana is at index 1 in the array [apple, banana, cherry]',
// 'cherry is at index 2 in the array [apple, banana, cherry]']
These above examples shows the map()
method can be used to transform each element of an array based on a specified function. Please keep in mind that map()
doesn’t change the original array, it returns a new array with the modified values. see more.
Thank you for reaching out this tutorial, you can comment for any issue and doubts in the below section.