reverse array

Reverse Array

Reversing an array means to flip the order of its elements. This can be achieved through various methods in programming. Let's take a look at some of them.

Method 1: Using a for loop

The simplest way to reverse an array is to create a new array and iterate over the original array in reverse order using a for loop. Here's how it can be done:

let arr = [1, 2, 3, 4, 5];
let revArr = [];

for (let i = arr.length - 1; i >= 0; i--) {
  revArr.push(arr[i]);
}

console.log(revArr); // Output: [5, 4, 3, 2, 1]

In this code, we first declare the original array arr. We then create an empty array revArr that will hold the reversed elements of the original array. We loop over the original array in reverse order using a for loop and push each element into the new array revArr. Finally, we print the reversed array to the console.

Method 2: Using the reverse() method

In JavaScript, arrays have a built-in method called reverse() that can be used to reverse the order of elements in an array. Here's how it works:

let arr = [1, 2, 3, 4, 5];

arr.reverse();

console.log(arr); // Output: [5, 4, 3, 2, 1]

In this code, we declare the original array arr and then call the reverse() method on it. This method reverses the order of elements in the array in place, which means that the original array is modified and no new array is created. Finally, we print the reversed array to the console.

Method 3: Using the spread operator and the reverse() method

We can also reverse an array using the spread operator and the reverse() method. Here's how:

let arr = [1, 2, 3, 4, 5];
let revArr = [...arr].reverse();

console.log(revArr); // Output: [5, 4, 3, 2, 1]

In this code, we first declare the original array arr. We then use the spread operator [...arr] to create a new array with the same elements as the original array. We then call the reverse() method on this new array to reverse its order. Finally, we assign the reversed array to the variable revArr and print it to the console.

These are some of the ways to reverse an array in JavaScript. Choose the one that works best for you depending on your use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe