How to sort flatlist in React Native?

情到浓时终转凉″ 提交于 2020-12-15 06:26:30

问题


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:


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.




回答2:


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


来源:https://stackoverflow.com/questions/60621248/how-to-sort-flatlist-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!