【问题标题】:Loadash orderby descending not working in JavaScript (React Native)Lodash orderby 降序在 JavaScript 中不起作用(React Native)
【发布时间】:2019-03-27 10:02:42
【问题描述】:

我正在从服务器获取数组,如下所示。

[
  {
    id: '508',
    class: 'class1',
    value: '6.0',
    percentage: '8.90',
    color: 'black'
  },
  {
    id: '509',
    class: 'class2',
    value: '14,916',
    percentage: '2.40',
    color: 'black'
  },
  {
    id: '510',
    class: 'class3',
    value: '14,916',
    percentage: '56.40',
    color: 'black'
  },
  {
    id: '511',
    class: 'class',
    value: '4,916',
    percentage: '2.40',
    color: 'black'
  }
]

从上面的列表中,我必须将最大百分比值显示为最低值。

所以,我尝试如下。

if (jsonData) {
      const sortedArray = orderBy(
        jsonData,
        ['percentage'],
        ['desc']
      );
      console.log('sortedArray is ', sortedArray);

}

它再次以相同的顺序出现,而不是从最大值到最小值。

有什么建议吗?

【问题讨论】:

  • 什么是orderBy
  • 你有奇怪的引用。这也不是有效的 JSON。此外,您正在比较 strings,因此您可能会得到这些字符串的顺序。
  • maximum percentage value to lowest ?和descending order ?我无法理解。请也发布预期的输出?
  • 从大到小排列的降序

标签: javascript sorting descendant


【解决方案1】:

我已更新您的帖子以使用实际的 javascript 字符串,但除此之外。您的百​​分比属性是字符串而不是数字,因此 lodash 的排序方式不同。要么确保百分比作为正确的数字从服务器返回,要么将它们映射到一个数字。

var data = [
  {
    id: '508',
    class: 'class1',
    value: '6.0',
    percentage: '8.90',
    color: 'black'
  },
  {
    id: '509',
    class: 'class2',
    value: '14,916',
    percentage: '2.40',
    color: 'black'
  },
  {
    id: '510',
    class: 'class3',
    value: '14,916',
    percentage: '56.40',
    color: 'black'
  },
  {
    id: '511',
    class: 'class',
    value: '4,916',
    percentage: '2.40',
    color: 'black'
  }
];

var correctedData = data.map( element => {
  // This will be a copy of every element, with the addition
  // of a new percentage value.
  // 
  var correctedElement = { 
    ...element,
    percentage: parseFloat(element.percentage)
  }
  return correctedElement;
});

var sortedArray = _.orderBy(correctedData, ['percentage'], ['desc']);

console.log(sortedArray)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

【讨论】:

    【解决方案2】:

    你可以简单地使用原生JS的sort函数

    let arr = [{ id: '508',class: 'class1',value: '6.0',percentage: '8.90',color: 'black' },{ id: '509',class: 'class2',value: '14,916',percentage: '2.40',color: 'black' },{ id: '510',class: 'class3',value: '14,916',percentage: '56.40',color: 'black' },{ id: '511',class: 'class4',value: '4,916',percentage: '2.40',color: 'black' }]
    
    let op = arr.sort(({percentage:A},{percentage:B})=>parseFloat(B) - parseFloat(A))
    
    console.log(op)

    【讨论】:

    • 有多个副本可用
    • 他的问题不是他的排序策略,而是他的数字是字符串。在我看来,指出这一点比简单地发布一段工作代码更有价值。但是很酷,您可以使用原生 JS 做到这一点:D!
    • @brk 在这种情况下,请关闭它们。你有锤子。
    猜你喜欢
    • 1970-01-01
    • 2018-05-28
    • 2021-02-02
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多