10

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...

1 Answer 1

27

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/

Sign up to request clarification or add additional context in comments.

6 Comments

return parseInt(obj.home, 10) ==> you can do return obj.home*1 and will make the trick without using parseInt
@ncubica: I think +obj.home is the more common shortcut.
but +obj.home will add string not numbers so as example if you have 10 (int) + "00" (str) result its gonna be 1000 but if you write 10 + ("00"*1) the result will be 10. which its what are you expecting right?
None of those apply here, we're just doing things like return +'10'. You're also dropping a +, the "unary plus to cast to number" version of 10 + '00'*1 would be 10 + +'00' (which requires you to be careful with your whitespace); in cases like this I'd use parseInt to make the intent crystal clear.
Can't understand what the matter is about parseInt: it is clearer for readers, so why should I complicate my code using a shortcut, to save a couple of bits?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.