【问题标题】:Sort array of object by key name 'val' , using lodash [duplicate]使用 lodash 按键名 'val' 对对象数组进行排序 [重复]
【发布时间】:2017-02-27 07:50:01
【问题描述】:

我有以下对象数组,我想对其进行排序。

     var points = [
{
    val: '0.10',
    text: '$0.10'
},
{
    val: '0.50',
    text: '$0.50'
},
{
    val: '1',
    text: '$1'
},
{
    val: '2',
    text: '$2'
},
{
    val: '3',
    text: '$3'
},
{
    val: '10',
    text: '$10'
},
{
    val: '20',
    text: '$20'
},
{
    val: '25',
    text: '$25'
},
{
    val: '50',
    text: '$50'
},
{
    val: '75',
    text: '$75'
},
{
    val: '100',
    text: '$100'
},
{
    val: '150',
    text: '$150'
},
{
    val: '200',
    text: '$200'
},
{
    val: '250',
    text: '$250'
},
{
    val: '300',
    text: '$300'
},
{
    val: '400',
    text: '$400'
},
{
    val: '1000',
    text: '$1,000'
},
{
    val: 'Other',
    text: 'Other'
}

]

我试过下面的排序功能-

        function myFunction() {
          points.sort(function(a, b){return a.val - b.val});
          console.log(points)
        }

但这会返回错误的输出。 我也尝试过使用 orderby 和 sortby 但仍然得到错误的输出。

_.orderBy(points,['val'],['asc'])

_.sortBy(points, 'val')

通过使用这两个选项,我得到了错误的排序值。

【问题讨论】:

  • numbersstrings 的排序不相等。您在 val 字段中有 strings
  • 我只是想做同样的事情@Rory McCrossan

标签: javascript jquery underscore.js lodash


【解决方案1】:

使用这种排序方法 -

points.sort(function(a,b){
 return parseInt(a.val)  - parseInt(b.val);
})

【讨论】:

  • 我写错了 (a-b) 。仍然得到错误的值
  • 使用 Number() 而不是 parseInt() 因为 parseInt() 会丢失精度
猜你喜欢
  • 2018-05-13
  • 2017-09-08
  • 2021-11-09
  • 2021-06-06
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 2020-10-11
  • 2023-01-19
相关资源
最近更新 更多