rashmi agar
25 posts
Mar 08, 2025
9:51 PM
|
I recently javascript reverse array and found several ways to do it. I wanted to share these methods with you and also hear if you have any other approaches. Let’s discuss the best way to reverse an array depending on the situation!
1. Using reverse() (Mutates the Original Array) The easiest way to reverse an array is by using the built-in reverse() method. This method directly modifies the original array.
javascript Copy Edit let arr = [1, 2, 3, 4, 5]; arr.reverse(); console.log(arr); // Output: [5, 4, 3, 2, 1] This is great if you want to reverse the array in place, but if you need to keep the original array unchanged, this might not be the best choice.
2. Using the Spread Operator and reverse() (Non-Mutating) If you want to avoid modifying the original array, you can create a copy using the spread operator (...) before applying reverse().
javascript Copy Edit let arr = [1, 2, 3, 4, 5]; let reversedArr = [...arr].reverse(); console.log(reversedArr); // Output: [5, 4, 3, 2, 1] console.log(arr); // Output: [1, 2, 3, 4, 5] (Original remains unchanged) 3. Using slice() and reverse() (Non-Mutating) Similar to the spread operator method, slice() can create a shallow copy before reversing.
javascript Copy Edit let arr = [1, 2, 3, 4, 5]; let reversedArr = arr.slice().reverse(); console.log(reversedArr); // Output: [5, 4, 3, 2, 1] 4. Using reduce() (Functional Approach) For those who like functional programming, reduce() can be used to reverse an array.
javascript Copy Edit let arr = [1, 2, 3, 4, 5]; let reversedArr = arr.reduce((acc, val) => [val, ...acc], []); console.log(reversedArr); // Output: [5, 4, 3, 2, 1] This method avoids modifying the original array but is slightly less efficient than reverse().
5. Using a for Loop (Manual Reversal) If you prefer a manual approach, a simple for loop can do the job.
javascript Copy Edit let arr = [1, 2, 3, 4, 5]; let reversedArr = []; for (let i = arr.length - 1; i >= 0; i--) { reversedArr.push(arr[i]); } console.log(reversedArr); // Output: [5, 4, 3, 2, 1] 6. Using map() with Index Manipulation Another approach is to use map() by accessing elements in reverse order.
javascript Copy Edit let arr = [1, 2, 3, 4, 5]; let reversedArr = arr.map((_, i, a) => a[a.length - 1 - i]); console.log(reversedArr); // Output: [5, 4, 3, 2, 1] Each of these methods has its use case. The reverse() method is the simplest and fastest for in-place modification, while slice(), spread operator, and reduce() are useful for keeping the original array intact.
|