JavaScript - Use map() on an Array in Reverse Order
Here are the different methods to use map() on an array in reverse order with JavaScript
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.
let a = [1, 3, 5, 7];
function gfg_Run() {
let new = a.slice(0).reverse().map(
function (val, index) {
return val * 2;
}
);
console.log(new)
}
gfg_Run();
Output
[ 20, 18, 14, 10, 6, 2 ]
In this example
- The code first creates a reversed copy of array a using slice(0).reverse() and then applies map() to multiply each element by 2.
- The transformed array is logged, where the elements of a are reversed and doubled.
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.
let a = [8, 5, 15, 70, 9];
function gfg_Run() {
let newArr = a.map(
(val, index, array) => 1 / 2 * array[array.length - 1 - index]
);
console.log(newArr);
}
gfg_Run();
Output
[ 4.5, 35, 7.5, 2.5, 4 ]
In this example
- The map() function processes each element by accessing the corresponding element from the array in reverse order (arr[arr.length - 1 - index]) and multiplying it by 1/2.
- The transformed array contains elements from the original array in reverse order, halved.
3. Using JavaScript loop in reverse order
Iterate over an array in reverse order using a for loop, starting from the last index and decrementing to zero.
let a = [8, 5, 15, 70, 9];
let rev= [];
for (let i = a.length - 1; i >= 0; i--) {
rev.push(a[i] * 2);
}
console.log(rev);
Output
[ 20, 18, 140, 30, 10, 16 ]
In this example
- The for loop iterates through array a in reverse order, multiplying each element by 2 and pushing the result into the rev array.
- The rev array contains the elements of a in reverse order, each doubled.
4. Using reduceRight()
The reduceRight() method processes the array from the last element to the first, making it a natural fit for reverse mapping.
let num = [1, 2, 3, 4, 5];
let rev = num.reduceRight((acc, num) => {
acc.push(num * 2);
return acc;
}, []);
console.log(rev);
Output
[ 10, 8, 6, 4, 2 ]
In this example
- reduceRight() iterates over the array in reverse order.
- For each element, the transformation is applied (num * 2), and the result is pushed into the accumulator array (acc).
5. Using forEach() as an Alternative
If you want to avoid using map() entirely, you can achieve a similar result using forEach() while iterating in reverse order.
let num = [1, 2, 3, 4, 5];
let rev = [];
num.forEach((num, i, arr) => {
rev.unshift(num * 2);
});
console.log(rev);
In this example
- The forEach() method processes the array in its original order, but unshift() is used to prepend the transformed elements, effectively reversing the result.