下划线_.sortBy无法正确排序数组对象

时间:2018-08-20 04:09:13

标签: javascript underscore.js

var Arr = [
             {size: "8"},
             {size: "9"},
             {size: "10"},
             {size: "7"},
             {size: "6"}
          ]

console.log(_.sortBy(Arr, 'size'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

我在上面的代码中创建了一个示例,该示例未能根据给定的数组正确排序。

3 个答案:

答案 0 :(得分:2)

您的尺寸属性是String类型,而不是Number类型。在JS中,引号("')中的值表示String类型。

给它们加上数字,它将正确排序。

var Arr = [
   {size: 8 },
   {size: 9 },
   {size: 10},
   {size: 7 },
   {size: 6 }
]

console.log(_.sortBy(Arr, 'size'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

答案 1 :(得分:2)

您需要将size更改为数字:

var Arr = [
             {size: "8"},
             {size: "9"},
             {size: "10"},
             {size: "7"},
             {size: "6"}
          ]

console.log(_.sortBy(Arr, (obj) => parseInt(obj.size)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

答案 2 :(得分:2)

这是字符串未按预期解释为数字的情况。以下是使用unary plus运算符进行投射的两种方法,有和没有_:

var Arr = [
             {size: "8"},
             {size: "9"},
             {size: "10"},
             {size: "7"},
             {size: "6"}
          ]

console.log(Arr.sort((a, b) => +a.size - +b.size));
console.log(_.sortBy(Arr, o => +o.size));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>