Tutorialspoint.dev

JavaScript | Array.prototype.map() function

Array.map()
arr.map() function creates a new array with the results of called function for every array element. This function calls the argument function once for each element of the given array in order. The syntax of this function is as follows:

Syntax:

var new_array = arr.map(arg_function(element[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

Arguments:
The argument to this function is another function that performs some operation on the original array elements and return elements to a new array. This function itself takes three arguments:

  • array : This is the array on which the .map() function was called.
  • index : This is the index of the current element being processed by the function.
  • element : This is the current element being processed by the function.

Another argument thisValue is used to tell the function to use this value when executing argument function.

Return value : This function returns a new array created by using the values modified by the arg_function using the valued from the original array. This function does not modify the original array on which this function is implemented.



Examples for the above function are provided below:

Example 1:

var arr = [2, 56, 78, 34, 65];
var new_arr = arr.map(function(num) {
  return num / 2;
});
print(new_arr);

Output:

[1, 28, 39, 17, 32.5]

In this example the function map() produces an array containing numbers obtained by dividing the numbers in original array by 2.

Example 2:

var arr = [10, 64, 121, 23];
var new_arr = arr.map(Math.sqrt);
print(new_arr);

Output:

[3.1622776601683795, 8, 11, 4.795831523312719]

In this example the function map() produces an array containing square roots of the numbers in original array.

Codes for the above function are provided below :

Program 1:

<script>
// JavaScript to illustrate map() function
  
function func() 
{
  // Original array
  var arr = [ 2, 56, 78, 34, 65 ];
  
  // new mapped array
  var new_arr = arr.map(function(num) { return num / 2; });
  
  document.write(new_arr);
func();
< /script>

Output:

1, 28, 39, 17, 32.5

Program 2:

<script>
//JavaScript to illustrate map() function
  
function func() 
{
    //Original array
    var arr = [10, 64, 121, 23];
  
    //new mapped array
    var new_arr = arr.map(Math.sqrt);
    document.write(new_arr);
}
func();
</script>

Output:

3.1622776601683795, 8, 11, 4.795831523312719


This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

1 Comments

load comments

Subscribe to Our Newsletter