reverse a sorted array in javascript

To reverse a sorted array in JavaScript, you can use the built-in reverse() method of the Array object. This method modifies the original array by reversing its elements in place.

index.tsx
const sortedArray = [1, 2, 3, 4, 5];
sortedArray.reverse();
console.log(sortedArray); // Output: [5, 4, 3, 2, 1]
113 chars
4 lines

If you do not want to modify the original array, you can create a new array and copy the elements of the original array in reverse order.

index.tsx
const sortedArray = [1, 2, 3, 4, 5];
const reversedArray = sortedArray.slice().reverse();
console.log(reversedArray); // Output: [5, 4, 3, 2, 1]
145 chars
4 lines

This creates a copy of the original array using the slice() method, and then uses the reverse() method to reverse the order of elements in the copy.

gistlibby LogSnag