How to Reverse an Array in React

avatar

Borislav Hadzhiev

Last updated: Apr 22, 2022

banner

Photo from Unsplash

Reverse an Array in React #

To reverse an array in React:

  1. Use the spread syntax (...) to create a shallow copy of the array.
  2. Call the reverse() method on the copy.
  3. Store the result in a variable.
App.js
export default function App() { const people = [ {name: 'Alice', country: 'Austria'}, {name: 'Bob', country: 'Belgium'}, {name: 'Carl', country: 'Canada'}, ]; // 👇️ create copy and reverse const reversed = [...people].reverse(); return ( <div> {reversed.map((person, index) => { return ( <div key={index}> <h2>Name: {person.name}</h2> <h2>Country: {person.country}</h2> <hr /> </div> ); })} </div> ); }

We used the spread syntax (...) to unpack the values of the array into a new array, creating a shallow copy.

This enables us to use the reverse() method without modifying the original array.

The Array.reverse method changes the contents of the original array in place.

App.js
const arr = ['a', 'b', 'c']; const reversed = arr.reverse(); console.log(reversed); // 👉️ ['c', 'b', 'a'] console.log(arr); // 👉️ ['c', 'b', 'a']

The reverse() method reverses an array in place and returns the result. This might not be the behavior you're looking for.

Notice that the original array stored in the arr variable was also reversed.

This is the reason we created a shallow copy in advance - to avoid changing the original array.

In general, it's best to avoid mutating arrays and objects in place because it makes your code confusing and difficult to follow.

Alternatively, you can use the Array.slice method.

To reverse an array in React:

  1. Call the slice() method on the array to create a shallow copy.
  2. Call the reverse() method on the copy.
  3. Store the result in a variable.
App.js
export default function App() { const people = [ {name: 'Alice', country: 'Austria'}, {name: 'Bob', country: 'Belgium'}, {name: 'Carl', country: 'Canada'}, ]; // 👇️ create copy and reverse const reversed = people.slice().reverse(); return ( <div> {reversed.map((person, index) => { return ( <div key={index}> <h2>Name: {person.name}</h2> <h2>Country: {person.country}</h2> <hr /> </div> ); })} </div> ); }

The first step is to create a shallow copy of the array by using the Array.slice method.

index.js
const arr = ['a', 'b', 'c']; const copy = arr.slice(); console.log(copy); // 👉️ ['a', 'b', 'c']

When the slice method is called without supplying any parameters, it returns a shallow copy of the original array.

Then we can call the reverse() method on the copy to avoid mutating the original array.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.