To reverse a list (or array) in JavaScript, we can use the reverse()
method. This method reverses the order of elements in the array, and it modifies the original array.
Here's an example:
index.tsx99 chars4 lines
In the above code, we first define an array called myArray
. Then, we call the reverse()
method on myArray
and store the reversed array back into myArray
. Finally, we log the contents of myArray
to the console, which should output [5, 4, 3, 2, 1]
as expected.
Note that the reverse()
method modifies the original array. If you don't want to modify the original array, you can make a copy of it first and then call the reverse()
method on the copy.
index.tsx182 chars5 lines
In the above code, we first make a copy of myArray
using the slice()
method, and store it in a new array called reversedArray
. Then, we call the reverse()
method on reversedArray
. Finally, we log both myArray
and reversedArray
to the console, which should output the original array followed by the reversed array.
gistlibby LogSnag