I have an array of objects and I want to sort ASC that array by the value of 'home'. That field is always numeric. So I've tried this:
_.sortBy(data.home.en, function(obj){ return obj.home });
That is working well when value of 'home' is lower then 10, but for some reason 10 goes just after the 1, so my final order looks like this 1,10,11,2,3,4,5,6,7,8,9 . Why is this happening? Thanks...
Your obj.home
values are strings so they're being compared as strings and '1' < '10'
is true. If you want to sort them like numbers then convert them to numbers:
_.sortBy(data.home.en, function(obj){ return +obj.home });
or:
_.sortBy(data.home.en, function(obj){ return parseInt(obj.home, 10) });
Demo: http://jsfiddle.net/ambiguous/DpfgV/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With