1

How to Reverse an Array in JavaScript

 2 years ago
source link: https://masteringjs.io/tutorials/fundamentals/reverse-array
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to Reverse an Array in JavaScript

Nov 30, 2021

To reverse an array in JavaScript, use the reverse() function. reverse() will mutate the original array so be mindful of this fact when using this function.

const array = [1, 2, 3, 4, 5];
array.reverse();
array; // [5,4,3,2,1]

Immutable Approach

You can use the reverse() function in combination with the slice() function or spread operator ... to prevent mutating the original array.

const array = [1, 2, 3, 4, 5];
const newArray = array.slice().reverse();
array; // [1,2,3,4,5]
newArray; // [5,4,3,2,1]
const array = [1,2,3,4,5];
const newArray = [...array].reverse();
array; // [1,2,3,4,5]
newArray; // [5,4,3,2,1]

More Fundamentals Tutorials


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK