Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array of objects using the underscore sortBy method

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

like image 712
hjuster Avatar asked Apr 27 '13 14:04

hjuster


Video Answer


1 Answers

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/

like image 61
mu is too short Avatar answered Feb 20 '23 07:02

mu is too short