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:
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
let arr = [1, 3, 5, 7, 9, 10];
function gfg_Run() {
let newArr = arr.slice(0).reverse().map(
function (val, index) {
return val * 2;
}
);
console.log(newArr)
}
gfg_Run();
|
Output[ 20, 18, 14, 10, 6, 2 ]
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
let arr = [8, 5, 15, 70, 9, 10];
function gfg_Run() {
let newArr = arr.map(
(val, index, array) => 1 / 2 * arr[arr.length - 1 - index]);
console.log(newArr);
}
gfg_Run();
|
Output[ 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
let arr = [8, 5, 15, 70, 9, 10];
let reverse = [];
for (let i = arr.length - 1; i >= 0; i--) {
reverse.push(arr[i] * 2);
}
console.log(reverse);
|
Output[ 20, 18, 140, 30, 10, 16 ]