Arulnadhan
Arulnadhan

Reputation: 921

How to sort Firebase Keys in ascending order?

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.

enter image description here

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

Upvotes: 3

Views: 1347

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598785

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.

Upvotes: 3

Related Questions