hju*_*ter 10 sorting underscore.js
我有一个对象数组,我想通过'home'的值来排序ASC那个数组.该字段始终为数字.所以我试过这个:
_.sortBy(data.home.en, function(obj){ return obj.home });
Run Code Online (Sandbox Code Playgroud)
当'home'的值低于10时,这很有效,但由于某种原因10在1之后,所以我的最终订单看起来像这样1,10,11,2,3,4,5,6,7 ,8,9.为什么会这样?谢谢...
mu *_*ort 27
您的obj.home
值是字符串,因此它们被比较为字符串并且'1' < '10'
是真的.如果你想像数字那样对它们进行排序,那么将它们转换为数字:
_.sortBy(data.home.en, function(obj){ return +obj.home });
Run Code Online (Sandbox Code Playgroud)
要么:
_.sortBy(data.home.en, function(obj){ return parseInt(obj.home, 10) });
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/ambiguous/DpfgV/1/