How to useindex parameter of JavaScript array.map() method in Javascript
The Javascript map() method in JavaScript creates an array by calling a specific function on each element present in the parent array.
Syntax:
map((element, index, array) => { /* … */ })
Example:
In this example, we will use the .map() method and call a function inside this method with 2 arguments (value, index). Now we need to access the value, we will access it from the reverse side (Eg. arr[arr.length – 1 – index]), this is an immutable operation (It doesn’t change the original array).
Javascript
// Creating new array let arr = [8, 5, 15, 70, 9, 10]; /* Main function */ function gfg_Run() { let newArr = arr.map( (val, index, array) => 1 / 2 * arr[arr.length - 1 - index]); // Disply output console.log(newArr); } // Function call gfg_Run(); |
[ 5, 4.5, 35, 7.5, 2.5, 4 ]
How to use map() on an array in reverse order with JavaScript ?
Given a JavaScript array and the task is to apply the map() method but on the reverse of the array efficiently. Here are a few approaches discussed. If you don’t want to change the original array then you can create a shallow copy of the array after that you can perform the task.