Javascript Array Map (with Example)

In this tutorial, you will learn about the javascript array map() method with the help of multiple examples.

The map() method in javascript is used to call a function for each and every element of an array. Using the javascript map() method we can apply changes to array elements like finding the square root, multiplying with a number, etc. 

As a result map() method provides a new array with modified array elements.

Example

let numbers = [1, 3, 4, 9, 8];

// function to square each number
function square(element) {
  return(element * element);
}

// square function on each element
let newArray = numbers.map(square);
console.log(newArray);
//Ouptut : [ 1, 9, 16, 81, 64 ]

Also Read:

Javascript Array Find
Javascript Array forEach
Javascript Array slice
Javascript Array splice

Array map() Syntax

arr.map(function(element, index, array), this)

Here arr is an array.

Array map() Parameters

function(): it is the function that will be called for each array element, and its return value will be added to the new array (Required).

element: it is the current element of the array (Required).

index: index of the current element (Optional);

array: array of the current element (Optional).

this: value to use as this when executing function (Optional).

Array map() Return Value

As a result, the Javascript map() method returns a new array with modified values returned by the function.

Note: map() method doesn’t change the original Array.

Example 1: Using Array map().

let number = [100, 200, 300, 400, 500];

//calculate square root
function squareRoot(value) {
    return Math.sqrt(value);
}

let newArray = number.map(squareRoot);

console.log(newArray);
// Output : 
// [ 10,
//   14.142135623730951,
//   17.320508075688775,
//   20,
//   22.360679774997898 ]

Output

[ 10,
14.142135623730951,
17.320508075688775,
20,
22.360679774997898 ]

Example 2: Using Array map() With an array of Objects.

CopyCopiedUse a different Browserlet number = [100, 200, 300, 400, 500];

//calculate square root
function squareRoot(value) {
    return Math.sqrt(value);
}

let newArray = number.map(squareRoot);

console.log(newArray);
// Output : 
// [ 10,
//   14.142135623730951,
//   17.320508075688775,
//   20,
//   22.360679774997898 ]

Output

[ 'Narendra Modi', 'Joe Biden', 'Emmanuel Macron' ]

Leave a Comment

Your email address will not be published. Required fields are marked *