I have data stored in a state that is shown in flatlist, I want to sort the data based on ratings. So if I click on sort button they should be sorted in ascending
order and when I click again, they should be sorted in descending
order.
I have an array of objects stored in state, below is just a piece of data that is important.
show_data_list = [{ ratings : { overall : 4, ...other stuff } } ]
Is there a way I could do it, I tried using the map function which sorts array
list.map((a,b) => a-b)
But how can I use this to sort my array of objects, I cant pass in 2 item.rating.overall
as the parameter.
Thanks in advance for the help :)
You can use javascript
's built in sort
function. You can provide a custom comparer
function for it, which should return a negative value if the first item takes precedence, 0 if they are the same and a positive value if the second value should take precedence.
show_data_list.sort((a, b) => { return a.ratings.overall - b.ratings.overall; })
. This will sort the data in the ascending order.
show_data_list.sort((a, b) => { return b.ratings.overall - a.ratings.overall; })
. This will sort it in the descending order.