JavaScript Array Map()

The map() method in JavaScript is used to create a new array by applying a given function to each element of the original array.

Syntax:

array.map(function_to_be_applied)
array.map(function (args) {
// code;
})

Example 1: In this example, we will transform each element by multiplying with 3.

Javascript




const numbers = [5, 10, 15, 20, 25, 30];
  
const multipliedNumbers = 
    numbers.map(num => num * 3);
console.log(multipliedNumbers)


Output

[ 15, 30, 45, 60, 75, 90 ]

Example 2: In this example, we will transform all values making them uppercase alphabets.

Javascript




const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'kiwi', color: 'green' },
    { name: 'orange', color: 'orange' },
    { name: 'pineapple', color: 'yellow' }
];
  
const transformedFruits = fruits.map(fruit => ({
    fruitName: fruit.name.toUpperCase(),
    fruitColor: fruit.color.toUpperCase()
}));
  
console.log(transformedFruits);


Output:

[
{ fruitName: 'APPLE', fruitColor: 'RED' },
{ fruitName: 'BANANA', fruitColor: 'YELLOW' },
{ fruitName: 'KIWI', fruitColor: 'GREEN' },
{ fruitName: 'ORANGE', fruitColor: 'ORANGE' },
{ fruitName: 'PINEAPPLE', fruitColor: 'YELLOW' }
]

Map() vs Filter() in Javascript

In JavaScript, the map() and filter() methods are powerful array functions that allow you to transform and filter arrays easily. We will discuss the required concepts about each method in this article.

Similar Reads

JavaScript Array Map()

The map() method in JavaScript is used to create a new array by applying a given function to each element of the original array....

JavaScript Array filter()

...

Differences of Map() and Filter() methods

...