Skip to main content

Sorting in React JS

Saleh is an experienced Web Developer and uses his knowledge and experience to guide people looking to learn Web Dev and new technologies

Sorting in React JS

Sorting in React JS

In this article, we will learn how to sort data in JavaSscript and how to implement it in React. Furthermore, we will be creating a simple sortable list with React as well.

Sorting Data in JavaScript

For sorting data in Javascript, we make use of the sort() function and its parameters. The most common application of sorting is when a list or table needs to be sorted alphabetically. There are a number of ways to achieve this.

Sorting an Array of Strings

Firstly, we will learn how to sort an array of strings (text).

Sorting A-Z

This is quite simple and the sort() function will automatically sort and array of strings A-Z. No other parameter is required in this case.

const data = ["Banana", "Orange", "Apple", "Mango"];
const sort = data.sort()
console.log(sort)
// ["Apple","Banana","Mango","Orange"]

Sorting Z-A

This is a little longer to achieve but quite simple. We will pass a function within the sort() that will sort the array into descending order.

There are a number of ways to achieve this.

1. Reversing the sorted Array To sort the array into descending order, we can simple reverse the array we sorted in ascending order.

const data = ["Banana", "Orange", "Apple", "Mango"];
const sort = data.sort().reverse()
console.log(sort)
//["Orange","Mango","Banana","Apple"]

2. Manually comparing using parameters

You can also run a function within the sort function that checks two items for the greater one and returns a value

const data = ["Banana", "Orange", "Apple", "Mango"];
const sort = data.sort((a, b) => (a > b ? -1 : 1))
console.log(sort)
//["Orange","Mango","Banana","Apple"]

We are using inline conditional statements here.

3. The localCompare function

The localeCompare() method returns sort order -1, 1, or 0 (for before, after, or equal).

Scroll to Continue

Read More From Owlcation

const data = ["Banana", "Orange", "Apple", "Mango"];
const sort = data.sort((a, b) => b.localeCompare(a))
console.log(sort)
//["Orange","Mango","Banana","Apple"]

Sorting an Array of Numbers

Sorting numbers in Javascript is pretty simple and can be done by running a compare function within the sort()

Sorting Numbers in Ascending Order

const data = [5,1,6,9,3];
const sort = data.sort((a, b) => a-b)
console.log(sort)
//[1,3,5,6,9]

Sorting Numbers in Descending Order

To sort them in descending order, we will simply reverse the comparison inside the return function.

const data = [5,1,6,9,3];
const sort = data.sort((a, b) => b-a)
console.log(sort)
//[9,6,5,3,1]

Creating a Sortable List With React JS

Now let's use the things we have learned above to create a functional demo. For this, we will create a simple list in React JS that will have an option to be sorted either in ascending or descending order using a dropdown.

Creating and Mapping an Array

First, in a new blank React app, we will create an array of strings which will be our list. Then we will map it out as an unordered list. We will also create the dropdown to select which type of sorting needs to be applied.

import { React, useState } from "react";
import "./App.css"

function App() {
  const data = ["Banana", "Orange", "Apple", "Mango"];

  return (
    <div className="main">
      <select defaultValue={'DEFAULT'}>
        <option value="DEFAULT" disabled>None</option>
        <option value="ascending">Ascending</option>
        <option value="descending">Descending</option>
      </select>
      <ul>
        {data.map((el, i) => (
          <li key={i}>{el}</li>
        ))}
      </ul>
    </div>
  );
}
export default App;

As you can see above, we are rendering out a dropdown and the mapped array in the form of a list.

Note: The default option is disabled in the dropdown, because we can not simply unsort the list once sorted.

Managing the States

Now we will need a state to store which type of sorting has been selected by the user. We will create a simple state and also an onchange function on the dropdown to set the state.

import { React, useState } from "react";
import "./App.css"

function App() {
  const data = ["Banana", "Orange", "Apple", "Mango"];
  const [sortState, setSortState] = useState("none");

  return (
    <div className="main">
      <select defaultValue={'DEFAULT'} onChange={(e) => setSortState(e.target.value)}>
        <option value="DEFAULT" disabled>None</option>
        <option value="ascending">Ascending</option>
        <option value="descending">Descending</option>
      </select>
      <ul>
        {data.map((el, i) => (
          <li key={i}>{el}</li>
        ))}
      </ul>
    </div>
  );
}
export default App;

Applying the Sorts

Lastly, we need to create an empty array of objects that will store each type of sort with its corresponding state name so that we can use it in the parameter of our sort() function.

This will be the final code:

import { React, useState } from "react";
import "./App.css"

function App() {
  const data = ["Banana", "Orange", "Apple", "Mango"];
  const [sortState, setSortState] = useState("none");

  const sortMethods = {
    none: { method: (a, b) => null },
    ascending: { method: undefined },
    descending: { method: (a, b) => (a > b ? -1 : 1) },
  };

  return (
    <div className="main">
      <select defaultValue={'DEFAULT'} onChange={(e) => setSortState(e.target.value)}>
        <option value="DEFAULT" disabled>None</option>
        <option value="ascending">Ascending</option>
        <option value="descending">Descending</option>
      </select>
      <ul>
        {data.sort(sortMethods[sortState].method).map((el, i) => (
          <li key={i}>{el}</li>
        ))}
      </ul>
    </div>
  );
}
export default App;

Result

Your sortable list will look like this now:

Result

Result

Thanks!

This content is accurate and true to the best of the author’s knowledge and is not meant to substitute for formal and individualized advice from a qualified professional.

© 2022 Saleh Mubashar

Related Articles