Five Ways to Reverse an Array in Javascript
We can reverse an array by both modifying the source array or without modifying the source array. We will look at different ways to do each.
Reversing an array by modifying the source array
We can use the reverse
method available to JavaScript arrays.
var numbers = [ '1️⃣' , '2️⃣', '3️⃣', '4️⃣', '5️⃣' ];
numbers.reverse();
console.log(numbers); // [5️⃣, 4️⃣, 3️⃣, 2️⃣, 1️⃣]
Reversing without modifying the original array
1.Using a normal for loop
var numbers = [ '1️⃣' , '2️⃣', '3️⃣', '4️⃣', '5️⃣' ];var reversedNum = [];for(let i = numbers.length -1; i >= 0; i--) { reversedNum.push(numbers[i]);
}
2. Using the map
method with the unshift
array method. unshift
pushes the value to the 0
th position of the array.
var numbers = [ '1️⃣' , '2️⃣', '3️⃣', '4️⃣', '5️⃣' ];var reversedNum = [];
numbers.map((val) => { reversedNum.unshift(val);});
3. Using slice
and reverse
var numbers = [ '1️⃣' , '2️⃣', '3️⃣', '4️⃣', '5️⃣' ];
var reversedNumbers = numbers.slice().reverse();
4. Using the spread operator and reverse
var numbers = [ '1️⃣' , '2️⃣', '3️⃣', '4️⃣', '5️⃣' ];
var reversedNumbers = [...numbers].reverse();
5. Using the spread operator and reduce
var numbers = [ '1️⃣' , '2️⃣', '3️⃣', '4️⃣', '5️⃣' ];
let reversedArray = [];numbers.reduce( (reversedArray, value) => { return [value , ...reversedArray];}, reversedArray);
There are manymore other ways to reverse an array in JS. Share your favorite or most interesting way to do it in the comments.
Do follow me Javascript Jeep🚙💨 .
Please make a donation here. 80% of your donation is donated to someone needs food 🥘. Thanks in advance.