invert an array in javascript

One way to invert an array in JavaScript is to use the reverse() method. This method changes the original array, so it is considered mutable.

Here's an example:

index.tsx
let arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); // Output: [5, 4, 3, 2, 1]
87 chars
4 lines

In this example, we declare an array arr with 5 elements. We then call the reverse() method on arr, which reverses the order of its elements. Finally, we log the resulting array to the console to confirm that it has been inverted.

Note that the reverse() method mutates the original array, so if you want to keep the original array intact, you should make a copy of it before calling reverse().

gistlibby LogSnag