Jason Shulenberger
Jason Shulenberger

Reputation: 23

firebase database order by value working wrong

So I have a database of stores and each store has a number in front of its name. They are added in a random order, but I want them displayed in order from 1 to 213. My problem is when I use orderbyvalue() it displays them like.

And so on. I need them it show up 1,2,3,4,5, etc instead of 1,10,11,12,13 etc.

What should I use to fix this?

Upvotes: 1

Views: 645

Answers (2)

MarsNoToshi
MarsNoToshi

Reputation: 200

The leading zeros may be a temporary solution but in regard of users experience this is wrong. You have to implement a sorting function. Moreover, if your system will have to deal with more than 999 stores, you won't have to touch your code for this.

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598785

As John commented, the order you get is expected: since you're storing strings, the nodes are ordered lexicographically.

If you want to order numerically, you either have to store the values as number or (in your case more likely) store the value in a format that orders the same lexicographically as numerically. E.g.

  • 01 Store
  • 02 Store
  • 10 Store
  • 11 Store
  • 19 Store
  • 20 Store
  • 21 Store
  • 22 Store

Or

  • 001 Store
  • 002 Store
  • 010 Store
  • 011 Store
  • 019 Store
  • 020 Store
  • 021 Store
  • 022 Store

This padding/prefixing of strings is quite normal in situations like this. One of the main disadvantages is that you'll have to determine how many characters to use for the numbers when you start your project.

Upvotes: 0

Related Questions