Dragonfly
Dragonfly

Reputation: 4361

Sorting a collection in backbone numerically

So I'm sorting items like this:

sorted_items = new Backbone.Collection items.sortBy((item) ->
  return item.get("position")
)

where items is already a collection. But I want sorted_items to be sorted by the field position which can be numbers from 1-1000. I know backbone sorts it alphabetically so right now its sorting it like: 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20... etc

Rather than 1, 2, 3, 4... etc

Now is there an easy way to do this or do I have to stick zeros before every position?

Upvotes: 0

Views: 634

Answers (1)

tilleryj
tilleryj

Reputation: 14379

It sounds like position is returning a string. You can either change your data source to make position an integer or use parseInt in your sort function:

return parseInt(item.get("position"), 10)

Upvotes: 1

Related Questions