How to sort data in object alphabetically in react js

How to sort data in object alphabetically in react js

Posted by Luke Beeno on July 22, 2022

How to sort data in object alphabetically in react js

How to sort data in object alphabetically in react js

Posted by Luke Beeno on July 22, 2022

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

Step 1. Create object

const arr = [{fruit:"orange"},
   {fruit:"pear"},
   {fruit:"banana"},
   {fruit:"grape"},
   {fruit:"lemon"},
   {fruit:"apple"}
]

Step 2. Create function

const compareStrings = (a, b) => {
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

Step 3. Create loop

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

In the example above the sort method has handed the arranging responsibility to the compareStrings function. Pass the object key to the function in order to arrange those values. 

All together:

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

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

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

export default App;

 

Any question?
This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question