Skip to content
the poor coder

reverse array without using another array

Poor Man
Published
Reading time
2 min read
On this page

Reverse Array without using another Array#

Reversing an array in JavaScript is a common task that we often come across while working with arrays. There are several ways to reverse an array, one of which is by modifying the same array without using another array.

Approach 1: Swapping elements#

The first approach involves swapping elements of an array. In order to reverse the array, we need to swap the first and last elements, then the second and second-last elements, and so on until we reach the middle of the array.

Text

function reverseArray(arr) {
  var len = arr.length,
      middle = Math.floor(len / 2),
      temp;

  for (var i = 0; i < middle; i++) {
    temp = arr[i];
    arr[i] = arr[len - 1 - i];
    arr[len - 1 - i] = temp;
  }

  return arr;
}

// Example usage
var arr = [1, 2, 3, 4, 5];
reverseArray(arr); // [5, 4, 3, 2, 1]

Approach 2: Using recursion#

The second approach involves using recursion to reverse the array. In this approach, we swap the first and last elements of the array, and then recursively call the same function on the remaining subarray until the entire array is reversed.

Text

function reverseArray(arr, start = 0) {
  var end = arr.length - 1 - start;

  if (start < end) {
    var temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;

    reverseArray(arr, start + 1);
  }

  return arr;
}

// Example usage
var arr = [1, 2, 3, 4, 5];
reverseArray(arr); // [5, 4, 3, 2, 1]

Conclusion#

Both approaches provide efficient ways of reversing an array in JavaScript. While the first approach is more straightforward and easier to understand, the second approach is more elegant and involves less code. Ultimately, it comes down to the programmer's preference and the specific use case.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC