0

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 :)

1

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

This is how I solved it stored the data in a variable and then sorted it based on condition

let rating = this.state.show_data_list;
      rating.sort(function(a,b) {
        return a.ratings.Overall < b.ratings.Overall

Comments

1

Try This

Sort your List Ascending/ Descending order with name or other string value in list

const [productSortList, setProductSortList] = useState(productarray);

where productarray is your main array

Ascending

productarray.sort((a, b) => a.products_name < b.products_name)

Descending

productarray.sort((a, b) => b.products_name < a.products_name),

You can reset the state of array you have passed as data in Flatlist

ascending ->   

setProductSortList(
   productarray.sort((a, b) => a.products_name < b.products_name),
);

do same for descending

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.