Working with Arrays can be a mess sometimes. In this tutorial, you will learn two ways to reverse an Array in JavaScript.
- First, using reverse() function
- Second, using a simple for loop
Using reverse() function
The easiest way to reverse an array in JavaScript is to use the reverse()
function. This function is built-in and is supported in all browsers.
The syntax is really easy, you just need to use a dot(.) operator with the array you want to reverse. Making a call to the reverse()
function.
Let’s see few JavaScript examples to reverse the array.
Example 1: Reverse a number Array
let array = [1,2,3,4,5,6,7]; // given array
array.reverse(); // using reverse method
console.log(array); // [7,6,5,4,3,2,1]
Example 2: Reverse an Array of Objects
let arrayObj = [
{name:'a', age:1},
{name:'b', age:2},
{name:'c', age:3}
];
arrayObj.reverse();
console.log(arrayObj);
// [ { name: 'c', age: 3 }, { name: 'b', age: 2 }, { name: 'a', age: 1 } ]
Whether the array contains a number, String or any objects, the reverse() function will always reverse it.
Note: The original array is overwritten with the value in reverse order.
What if, you want to reverse an array without using a library/in-build function.
Using for Loop to Reverse an Array in JavaScript
As you know, We can use a loop to traverse through an array. Therefore, the value in an array can be obtained in the desired way we want.
Let’s use for loop to reverse an array. Moreover, we need a reverse for loop.
As we want elements starting from the last index to the very first index. And an empty array for storing the values from the original array.
let array = ['a','b','c','d','e']; // orignal array
let reverseArray= []; // an emplty array
let index=0; // helper index
for ( let i=array.length-1; i>=0; i--){ // reverse loop
reverseArray[index]=array[i]; // save values from last index
index++; // increment index
}
console.log(reverseArray);
In the above example, the loop started from (array.length-1) which is the last index, and loops until the index becomes greater than equal (>=) to zero .i.e the very first index.
Finally, we hope this tutorial helped you to reverse an array. Let us know in the comments if you face any doubts.
Also, You may be interested to learn how to check for Duplicates in Array JavaScript
Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed