How to use .map() to iterate through array items

Instead of manually iterating over the array using a loop, we can use the built-in Array.map() method.

In this article, we will cover map() syntax and how to use map() over an array of objects.

I. What is map() function?

map() is one of the most used and popular Javascript array method.

It allows us to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each of the array’s elements.

map() always returns a new array. It doesn’t change the size of the original array unlike filter().

II. map() syntax

The syntax of the forEach() method is:

arr.map(function(currentElement, index, array){  }, this);
  • currentElement: the value of current element
  • index: array index of current element (optional)
  • array: the array object where the current element belongs (optional)

III. How to use map() over an array

For example, we have an array that stores firstName and lastName.

let people = [
  {firstName : "Anna", lastName: "Smith"},
  {firstName : "John", lastName: "Doe"},
  {firstName : "Peter", lastName: "George"}
];

We can use the map() method to iterate over the array and return the combination of firstName and lastName:

let people = [
  {firstName : "Anna", lastName: "Smith"},
  {firstName : "John", lastName: "Doe"},
  {firstName : "Peter", lastName: "George"}
];

let fullNames = people.map(function(item){
    return `${item.firstName} ${item.lastName}`;
})

console.log(fullNames);
// ["Anna Smith", "John Doe", "Peter George"]

IV. For loop vs. map

Logically, map() is quite similar as a for loop.

However, with map(), we don’t need to run a loop to call out each value to add. We simply need to state what we need and return it.

// using for loop

let arr = [1, 2, 3, 4];
let plus5 = [];
for(let i = 0; i < arr.length; i++) {
  plus5[i] = arr[i] + 5;
}
console.log(plus5) // [6, 7, 8, 9]
// using map

let arr = [1,2,3,4];
let plus5 = arr.map((val,i,arr) => {
  return val + 5;
});
console.log(plus5) // [6, 7, 8, 9]

V. How to use index in Map()

The index in map() method provides the position of each element in an array, but it doesn’t change the original array.

Example

let names = ["Anna", "John", "Peter"];

names.map((name, index) => console.log(`The ${index} is ${name}`));

Output:

The 0 is Anna
The 1 is John
The 2 is Peter

V. Interact with objects in an array

Example 1: Check object with a condition

In this example, we interact with an array based on a condition.

We check if each object is even or not before we double its value. Initial values in array that do not satisfy the condition will not change the value.

let arr = [1, 2, 3, 4, 5];
let newArr = arr.map((value, index, arr) => {
  return value % 2 === 0 ? value * 2 : value;
});

console.log(newArr);
// [1, 4, 3, 8, 5];

Example 2: Construct a new array of objects

For example, we have an array:

const people = [
  {
    name: "Anna",
    age: 35,
    position: "Designer",
  },
  {
    name: "John",
    age: 20,
    position: "Web developer",
  },
  {
    name: "Peter",
    age: 26,
    position: "CEO",
  },
];

We can construct a new array:

const newPeople = people.map((item) => {
  return {
    firsName: item.name.toUpperCase(),
    oldAge: item.age + 30,
  };
});

console.log(newPeople);
// [{firsName: "ANNA", oldAge: 65}, {firsName: "JOHN", oldAge: 50}, {firsName: "PETER", oldAge: 56]