DEV Community

Michael Adeleke Olomola
Michael Adeleke Olomola

Posted on

JavaScript Array Map()

Map() is an array method that applies a function we provide to each element of an array and creates a new array with the result.

Example

const products = ['Burger', 'Beef’, 'Pizza', 'Chicken']
const mappedProducts = products.map (product = '${product}*')

console.log(mappedProducts) 

// Output: ['Burger *', 'Beef *', 'Pizza *', 'Chicken *']

Enter fullscreen mode Exit fullscreen mode

The Map() method takes an array of elements and returns a new array after transforming the element based on a function we supplied.

In simple English, this line of code is:
Given an array called products, take each element in the array and add an asterisk to it. Then return a new array with all the transformed elements. When finished, store the new array in a variable called'mappedProducts'.

How to map an array without the map() method
To map an array without using the map() method, you can use a for loop to iterate through each element of the array.

Example

const number = [2, 4, 6, 8, 10]
const mappedNumbers = [ ];

for (let i = 0; i < numbers.length; i++) {
   mappedNumbers.push(numbers[ i ] * 2);
}

console.log(mappedNumbers);

// output: [4, 8, 12, 16, 20]
Enter fullscreen mode Exit fullscreen mode

This example shows the number of arrays [2, 4, 6, 8, 10].

You create an empty array called mappedNumbers to store the mapped values. Use a for loop to iterate through each element of the number array and multiply by 2.

Push the result value into the mappedNumbers array. Finally, log the mappedNumbers array to the console, which gives you the mapped array [4, 8, 12, 16, 20].

Top comments (0)