javascript - 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);
}
它再次以相同的顺序出现,而不是从最大值到最小值排序。
有什么建议么?
解决方案
我已更新您的帖子以使用实际的 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>
推荐阅读
- javascript - vue.js 中父组件的删除函数
- testng - 如果测试响应为 x 或 y,则自动更改测试流程
- php - Behat 测试挂在模态按钮上
- javascript - Material-UI 数据网格日期选择器
- ios - 与 Parse 服务器(在 iOS 上使用 Swift)交谈时,为什么 PFFileObject 一直返回 nil?
- kubernetes - 无法使用 kubectl 连接到我的私有集群(无法连接到服务器:拨号 tcp)
- javascript - JS Doc,有没有办法指定“Choice”参数?
- python - 满足条件时如何在字符之间添加空格?
- javascript - 缺少资源的全局 JavaScript 事件
- python - Pytorch 张量操作给了我不同的输出