Hey guys š if you have heard about the map method but donāt understand it or know what it can do, Then this article is for you. Letās dive right into it.
What IsĀ map
method?
TheĀ map
is an array method that allows you to iterate through all the elements in an array and create a brand new array of values from the original array without changing the original array.
Letās see an example šš½
const students = [
{
name: 'John',
age: 22,
},
{
name: 'Doe',
age: 25,
},
{
name: 'Smith',
age: 27,
},
];
We first created an array of objects (students) with their name and age. Now, we are going to create a new array of name using the map
method without changing the original array we just created.
const studentName = students.map((student) => student.name);
console.log(studentName); //return ['John', 'Doe', 'Smith']
If you observe carefully, youāll see that theĀ map
method does notĀ change the array you callĀ map
Ā on. Instead it creates a brand new array which is returned fromĀ map
. In the above example theĀ students
Ā array is never actually changed and still contains the students objects with their name and age.
When we first callĀ map
Ā , we pass it our function and theĀ map
method will take the first element of ourĀ students
Ā array and pass it to the function (which is studentName
) we pass toĀ map
. In our case that means that the first element in ourĀ students
array will be set toĀ student
. This function will then run and return a value which in our case is the students
name. That value will be stored as the first element in a new array. Then this entire process repeats with the next element in our array all the way until we have no more elements. Finally, onceĀ map
is done looping through our array, it will return a brand new array of elements that are equal to the return values of the function we pass toĀ map
.
Another thing to note is that the map
method can take up to two parameter just like the forEach
method. Letās see another example šš½
const ages = [22, 4, 5, 6, 3];
// Subtract the elements inside the array by 2 and get the index
const SubtractAge = ages.map((age, index) => {
console.log(index);
// 0
// 1
// 2
// 3
// 4
return age - 2;
});
console.log(SubtractAge); // [20, 2, 3, 4, 1]
As you can see above we are using the second parameter of the function which is our index and it is printing out the index (and index always start from 0) of the current element we are on which in this example itās printing 0 - 4 . This is useful if you need to do something based on the index of the element in theĀ map
.
š¼ 3 Use Cases for Map Array
There are many use cases for the map array method, but in this article we will only focus on three of them;
š² Callback certain elements in an array
Just as the name implies, You can literally call certain elements in array. Letās see an example šš½
const ages = [22, 4, 5, 6, 3];
const evenNum = ages.map((age) => {
if (age % 2 === 0) {
return Math.sqrt(age);
} else {
return age;
}
});
console.log(evenNum); // [4.69041575982343, 2, 5, 2.449489742783178, 3]
As you can see in this example, Instead of getting the square root of all the element in the array, you can get the square root of the specified elements if they are even.
Just a bonus here, You can write the same code using the ternary operator šš½
const ages = [22, 4, 5, 6, 3];
const evenNum = ages.map((age) => {
return age % 2 === 0 ? Math.sqrt(age) : age;
});
console.log(evenNum); // [4.69041575982343, 2, 5, 2.449489742783178, 3]
āæ Double the elements of an array
You can create a new array from another array using theĀ map()
method just like the example you we used at the beginning of the article. For example, you can double the elements of an integer array and create a new array from the initial array. Letās see an example.
const normalAge = [22, 4, 5, 6, 3];
const doubleAge = normalAge.map((age) => age * 2);
console.log(normalAge); // [22, 4, 5, 6, 3]
console.log(doubleAge); // [44, 8, 10, 12, 6]
š Reformat objects in an array
You can reformat an array of objects using theĀ map()
method. Letās see an example šš½
const students = [
{
firstname: 'John',
lastname: 'Doe',
},
{
firstname: 'Mark',
lastname: 'James',
},
{
firstname: 'Peter',
lastname: 'Pan',
},
];
// Reformat the objects in the array
const addNames = students.map((student) => {
let newObj = {};
newObj['Fullname'] = `${student.firstname} ${student.lastname}`;
return newObj;
});
console.log(addNames);
// {Fullname: 'John Doe'}
// {Fullname: 'Mark James'}
// {Fullname: 'Peter Pan'}
In this example above, we created an array of objects that contains the first and last names of the students. Then, we created a new array calledĀ addNames
to join the first and last names of each student.
If you are still the type like me that wondered (or is wondering) how this concept can be applied to real world project, Here is a link to mini ecommerce website I built that tells you to click and see the discount of a price (while you donāt have to set it manually on your html documents especially if you have tons of product š ).
https://arraysmethod.netlify.app/
https://github.com/dev-lawrence/Array-methods
Thatās all guys š. Hope you learned something from this article. See you next time
Top comments (0)