How to sort array alphabetically in react js

How to sort array alphabetically in react js

Posted by Luke Beeno on July 21, 2022

How to sort array alphabetically in react js

How to sort array alphabetically in react js

Posted by Luke Beeno on July 21, 2022

This short lesson will show you how to arrange data in an array alphabetically in React.

Step 1 Create array

const arr = [
  "orange",
  "pear",
  "banana",
  "grape",
  "lemon",
  "apple"
]

Step 2. Loop through array

arr.sort().map((item, a) => {
  return <div key={a}>{item}</div>
})

If you notice above the sort method is used with map to do the arranging as it loops.

or

If you want to do some kind of action before you sort, like turn all the strings to lower case. Use a function within the sort method.

Sort function:

const compareStrings = (a, b) => {
  //do something i.e. a.toLowerCase(); b.toLowerCase()
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

Then loop:

arr.sort((a, b) => compareStrings(a, b)).map((item, a) => {
  return <div key={a}>{item}</div>
})

In the example above the sort method has handed the arranging responsibility to the compareStrings function. 

All together:

function App() {
    const arr = [
        "orange",
        "pear",
        "banana",
        "grape",
        "lemon",
        "apple"
    ]

    const compareStrings = (a, b) => {
        //do something i.e. a.toLowerCase(); b.toLowerCase()
        return (a < b) ? -1 : (a > b) ? 1 : 0;
    }

  return (
      arr.sort((a, b) => compareStrings(a, b)).map((item, a) => {
         return <div key={a}>{item}</div>
      })
  );
}

export default App;