Saleh is an experienced Web Developer and uses his knowledge and experience to guide people looking to learn Web Dev and new technologies
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 an Array of Strings
Firstly, we will learn how to sort an array of strings (text).
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.
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.
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
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).
Read More From Owlcation
Sorting an Array of Numbers
Sorting Numbers in Ascending Order
Sorting Numbers in Descending Order
To sort them in descending order, we will simply reverse the comparison inside the return function.
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.
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.
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:
Your sortable list will look like this now:
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