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.
Approaches to use array.map() in reverse order:
- Using JavaScript array.reverse() method
- Using index parameter of JavaScript array.map() method
- Using JavaScript loop in reverse order
Approach 1: Using JavaScript array.reverse() method
The idea is to use the .reverse() method just after applying the .slice() method. Then use the .map() method on the reversed array to perform the task.
Syntax:
arr.reverse()
Example:
This example implements the above approach.
Javascript
// Creating new array let arr = [1, 3, 5, 7, 9, 10]; /* Main function */ function gfg_Run() { let newArr = arr.slice(0).reverse().map( function (val, index) { return val * 2; } ); // Display output console.log(newArr) } // funtion call gfg_Run(); |
[ 20, 18, 14, 10, 6, 2 ]
Approach 2: Using index parameter of JavaScript array.map() method
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 ]
Approach 3: Using JavaScript loop in reverse order:
Example:
In this example, we will iterate the array in reverse order using for loop and multiply each number by 2 and store it in the reverse array.
Javascript
// Creating new array let arr = [8, 5, 15, 70, 9, 10]; // variable to store the result let reverse = []; // Loop in reverse order for (let i = arr.length - 1; i >= 0; i--) { reverse.push(arr[i] * 2); } // Display the output console.log(reverse); |
[ 20, 18, 140, 30, 10, 16 ]