How to reverse an array in JavaScript in place

JavaScript Array.reverse() method to reverse an array in place:

JavaScript Array.reverse() method can be used to reverse an array in-place. In this post, we will learn how to use reverse method with examples.

Definition of reverse() method:

The reverse() method can reverse the content of an array in place. It is defined as like below:

arr.reverse()

It returns the reversed array. Since it changes the content of the original array, if we print the array, it will be reversed.

Example of reverse():

Let’s try reverse with an example:

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

console.log('arr before reverse: ', arr);

arr.reverse();

console.log('arr after reverse: ', arr);

If you run this program, it will print the array arr, reverse the array and print it again.

arr before reverse:  [
  1, 2, 3, 4,
  5, 6, 7
]
arr after reverse:  [
  7, 6, 5, 4,
  3, 2, 1
]

JavaScript array reverse

Example 2: Reverse an array without using reverse():

We can also reverse an array with a loop and put the content in another array. It will not change the array in place:

const reverseArray = (arr) => {
  let rev = [];

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

  return rev;
};

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

console.log("arr before reverse: ", arr);

let rev = reverseArray(arr);

console.log("arr after reverse: ", rev);

The reverseArray method uses a for loop to reverse the content of the array it receives as the parameter. The for loop iterates from end to start of the array. rev is an empty array initialized to hold the final reversed array. Inside the for loop, we are adding the elements to rev. Once the loop ends, rev will hold the reverse array.

It will print the same output.

Example 3: Using reverse with an array like objects:

We can use reverse() with an array like object. For example, if the object contains elements with index values and a length property, reverse() will work.

Let’s take a look at the below program:

let givenObj = { 0: 10, 1: 11, 2: 13, 3: 14, 4: 21, length: 5 };

console.log("Before reverse(): ", givenObj);

Array.prototype.reverse.call(givenObj);

console.log("After reverse(): ", givenObj);

It will reverse the array:

Before reverse():  { '0': 10, '1': 11, '2': 13, '3': 14, '4': 21, length: 5 }
After reverse():  { '0': 21, '1': 14, '2': 13, '3': 11, '4': 10, length: 5 }

You might also like: