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)