DEV Community

Cover image for Map Array Method
Amrasakpare Lawrence
Amrasakpare Lawrence

Posted on

Map Array Method

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,
  },
];

Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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Ā studentsarray 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]

Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

āžæ 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]
Enter fullscreen mode Exit fullscreen mode

šŸ“„ 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'}
Enter fullscreen mode Exit fullscreen mode

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Ā addNamesto 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)