There are several ways to reverse an array in JavaScript. One of the simplest ways is to use the built-in reverse()
method that mutates the original array. Here's an example:
index.tsx87 chars4 lines
Note that reverse()
reverses the elements in place and returns a reference to the original array, so there's no need to assign the result to a new variable.
If you want to create a reversed copy of the array without mutating the original one, you can use the slice()
and reverse()
methods together. Here's an example:
index.tsx154 chars5 lines
In this case, slice()
creates a shallow copy of the array so that the original one is not affected, and then reverse()
reverses the elements of the copied array.
Alternatively, you can use a for loop to copy the elements of the original array in reverse order into a new one. Here's an example:
index.tsx208 chars8 lines
This approach is more verbose than the previous ones, but it also gives you more control over how the reversed array is created.
gistlibby LogSnag