Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To sort array of string in react js, use the sort() method with localeCompare() method it will sort array and return new array based on your condition.

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending.

The localeCompare() method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order.

For the sort array of strings alphabetically, let’s take an example of strings array.

var items = ['infinitbility', 'aguidehub', 'sortoutcode'];


items.sort((a, b) =>
   a.localeCompare(b)//using String.prototype.localCompare()
);

// 👇️ Output
//   ['aguidehub', 'infinitbility', 'sortoutcode']

Today, I’m going to show you How do I sort array of string in react js, as above mentioned here, I’m going to use the sort() method with localeCompare() method.

Let’s start today’s tutorial how do you sort array of string in react js?

In this example, we will do

  1. create a sample array of strings state
  2. used sort function to sort state
  3. update the state with sorted array
  4. print the array on screen

Let’s write code…

import React, { useState, useEffect } from "react";
export default function App() {
    const [arr, setArr] = useState(['infinitbility', 'aguidehub', 'sortoutcode']);

     useEffect(() => {
        // sort the array
        var items = [...arr];
        items.sort((a, b) =>
            a.localeCompare(b)
        );
        setArr(items);
    }, []);

  return (
    <div className="App">
      <p>{JSON.stringify(arr)}</p>
    </div>
  );
}

As mentioned above, we are taken the example of a array of string state, used the sorting methods to sort array of string and print the output.

I hope it’s help you, All the best 👍.