JavaScript provides several powerful methods to manipulate arrays. Among these, map
is one commonly used. Let's dive into how this method works and how it can be used effectively.
Map
The map
method creates a new array by applying a function to each element of the original array. It returns a new array with the transformed elements.
const myNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const newNums = myNumbers.map( (num) => num + 10 );
console.log(newNums);
//outputs:
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Performing above code with for each
const newValue = [];
myNumbers.forEach(dum => {
if(dum < 11){
dum = dum * 10 + 1;
if (dum > 40) {
newValue.push(dum);
}
}
});
console.log(newValue); // Output: [51, 61, 71, 81, 91, 101]
//outputs:
[51, 61, 71, 81, 91, 101]
Chaining of array methods
const newNums = myNumbers.map(num => num * 10).map(num => num + 1)
.filter(num => num > 40);
console.log(newNums);
//outputs:
[41, 51, 61, 71, 81]
Here, we first multiply each element by 10, then add 1 to each result, and finally filter out values greater than 40.