reverse an array in typescript

To reverse an array in Typescript, we can use the reverse() method provided by arrays. The reverse() method permanently changes the original array, mutating it in place.

index.ts
const arr: number[] = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); // Output: [5, 4, 3, 2, 1]
99 chars
4 lines

If we want to create a new array with reversed elements without changing the original, we can create a copy of the original array using the spread operator (...) and then reverse the copied array.

index.ts
const arr: number[] = [1, 2, 3, 4, 5];
const reversedArr = [...arr].reverse();
console.log(reversedArr); // Output: [5, 4, 3, 2, 1]
console.log(arr); // Output: [1, 2, 3, 4, 5]
177 chars
5 lines

gistlibby LogSnag