首页 > 解决方案 > Loadash orderby 降序在 JavaScript 中不起作用(React Native)

问题描述

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

[
  {
    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);

}

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

有什么建议么?

标签: javascriptsortingdescendant

解决方案


我已更新您的帖子以使用实际的 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>


推荐阅读