Reverse an Array in JavaScript
2 min readMay 8, 2022
Different methods to reverse the array elements using JavaScript
Built in reverse() method:
- This is the simplest method to reverse an array in place (constant space complexity).
Output: [5, 4, 3, 2, 1]
2. Swapping elements in place in the array:
- This function should accept an array as an argument.
- Create two pointers start, end.
- Start points at 0th index and end points at the index of the last element of the array (array.length — 1).
- Loop through the array and swap elements at both of these indexes.
- Increment start by one and decrement end by one.
- Stop the loop when start ≥ end.
- Return the array.
Output: [5, 4, 3, 2, 1]
3. Using For loop:
- Function should take an array as an argument.
- Create a new array to store the values.
- Traverse through the given array backwards and push each element in the new array.
- Return the new array.
Output: [5, 4, 3, 2, 1]
Note: These are some similar approaches you can use to do the second method.
- unshift: loop through the entire array from the starting (or use map method) and unshift each value in the new array. (Remember, unshift is a costly operation in arrays)
- while loop: same algorithm can be implemented with while loop too.
4. Using Map and Spread:
- The map() method maps each popped element (removed last element) from the arr and pushes it into a new array, which is created as a copy of arr.
- By removing the last element and adding it as the first into a new array, we create a new reversed array.
Output: [5, 4, 3, 2, 1]
Also, read