Javascript

Reverse an array using JavaScript

In this article, we look at different methods to reverse the array elements using JavaScript. Using the reverse method As the name...

Written by Luci · 1 min read >

In this article, we look at different methods to reverse the array elements using JavaScript.

Using the reverse method

As the name suggests, this method reverses the order of array elements by modifying the existing array.

Syntax:

array.reverse()

Example:

arr = [1,2,3,4];
arr.reverse();
console.log(arr);

//Output: [ 4, 3, 2, 1 ]
Using a decrementing For Loop
arr = [1, 2, 3, 4];
arr1 = [];
for (let i = arr.length - 1; i >= 0; i--) {
    arr1.push(arr[i]);
}
console.log(arr1);

//Output: [4, 3, 2, 1]

In the above example, we use a decrementing loop to traverse the array arr from backward and store each element to the new array arr1. This method does not modify the original array.

Using the Unshift() Method
arr = [1, 2, 3, 4];
arr1 = [];
arr.forEach(element => {
    arr1.unshift(element)
});
console.log(arr1);

//Output: [4, 3, 2, 1]

This method is very similar to the previous method and does not modify the original array. Instead of using a for loop, this method uses forEach() & unshift() methods. forEach() method performs an operation for each element of an array and the unshift method adds a new element to the beginning of an array.

Without using a new array or the reverse() method

In the previous two methods, we did not modify the existing array and stored the reversed elements in a new array. Now, we shall look at how one can reverse and modify an existing array without using the reverse method.

arr = [1, 2, 3, 4];
for (let i = 0; i < Math.floor(arr.length / 2); i++) {
    [arr[i], arr[arr.length - 1 - i]] = [arr[arr.length - 1 - i], arr[i]];
}
console.log(arr);

//Output: [4, 3, 2, 1]

In this method, we traverse only one half of the length of the given array and swap the elements in equal distance from first and the last i,e, first element and last and second with second last and so on.

Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x