Sort an Array of Objects in React

avatar

Borislav Hadzhiev

Fri Apr 22 20222 min read

banner

Photo by Jeremy Bishop

Sort an Array of Objects in React #

To sort an array of objects in React:

  1. Create a shallow copy of the array.
  2. Call the sort() method on the array passing it a function.
  3. The function is used to define the sort order.
App.js
export default function App() { const employees = [ {id: 4, name: 'Dean', country: 'Denmark'}, {id: 3, name: 'Carl', country: 'Canada'}, {id: 2, name: 'Bob', country: 'Belgium'}, {id: 1, name: 'Alice', country: 'Austria'}, {id: 5, name: 'Ethan', country: 'Egypt'}, ]; // 👇️ sort by Numeric property ASCENDING (1 - 100) const numAscending = [...employees].sort((a, b) => a.id - b.id); console.log(numAscending); // 👇️ sort by Numeric property DESCENDING (100 - 1) const numDescending = [...employees].sort((a, b) => b.id - a.id); console.log(numDescending); // 👇️ sort by String property ASCENDING (A - Z) const strAscending = [...employees].sort((a, b) => a.name > b.name ? 1 : -1, ); console.log(strAscending); // 👇️ sort by String property DESCENDING (Z - A) const strDescending = [...employees].sort((a, b) => a.name > b.name ? -1 : 1, ); console.log(strDescending); return ( <div> {numAscending.map(employee => { return ( <div key={employee.id}> <h2>id: {employee.id}</h2> <h2>name: {employee.name}</h2> <h2>country: {employee.country}</h2> <hr /> </div> ); })} </div> ); }

The examples show how to sort an array of objects in ascending and descending order for numeric and string properties.

The Array.sort method mutates the original array, so we used the spread syntax (...) to create a shallow copy of the array before calling sort().

The parameter we passed to the sort method is a function that defines the sort order.

The sort() method uses the following logic to sort the elements in the array:

  • If the return value of the compare function is greater than 0, then sort b before a.

  • If the return value of the compare function is less than 0, then sort a before b.

  • If the return value of the compare function is equal to 0, keep the original order of a and b.

You can use the Array.map method to render the sorted array.

App.js
export default function App() { const employees = [ {id: 4, name: 'Dean', country: 'Denmark'}, {id: 3, name: 'Carl', country: 'Canada'}, {id: 2, name: 'Bob', country: 'Belgium'}, {id: 1, name: 'Alice', country: 'Austria'}, {id: 5, name: 'Ethan', country: 'Egypt'}, ]; return ( <div> {[...employees] .sort((a, b) => a.id - b.id) .map(employee => { return ( <div key={employee.id}> <h2>id: {employee.id}</h2> <h2>name: {employee.name}</h2> <h2>country: {employee.country}</h2> <hr /> </div> ); })} </div> ); }

We chained a call to the map() method immediately after sorting. This enables us to avoid storing the sorted array in an intermediary variable if we only need to render it.

Use the search field on my Home Page to filter through my more than 1,000 articles.