How to sort Firebase Keys in ascending order?

本秂侑毒 提交于 2020-01-02 08:19:09

问题


I have a list of products in my Firebase Database. My SKU looks like this c08p10. But the problem is that Hundred product is shown after the tenth product.

Please refer the screenshot for the jumbled product order.

I can understand that the products are arranging alphabetically. But how can i display the products in the below order

c08p10
c08p11
c08p12

NOTE

I can populate the data in a List view or recycler View. But the products are arranged in the firebase DB order. If I try to reverse the order. It gives the below structure.

c08p118
c08p117
c08p116

回答1:


Firebase keys are strings. And when you order string data, it is ordered lexicographically.

So for numbers, this is the normal order:

  • 1
  • 9
  • 10
  • 11

But for strings, this is the normal order:

  • "1"
  • "11"
  • "19"
  • "9"

There is no operator in Firebase (nor in most other databases) to change this behavior. Instead, you will have to modify the data to get the behavior you want. So: store values that are in the order you need them when sorted lexicographically. For numbers you can accomplish that by padding them with zeroes:

  • "001"
  • "009"
  • "011"
  • "019"

Or in your case c09p010, etc.



来源:https://stackoverflow.com/questions/43275688/how-to-sort-firebase-keys-in-ascending-order

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