user12551649
user12551649

Reputation: 426

How to sort flatlist in React Native?

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

Upvotes: 0

Views: 10172

Answers (3)

Arnold Brown
Arnold Brown

Reputation: 1433

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

Upvotes: 1

user12551649
user12551649

Reputation: 426

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

Upvotes: 3

giotskhada
giotskhada

Reputation: 2452

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.

Upvotes: 4

Related Questions