我正在从服务器获取阵列,如下所示。
[
{
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);
}
它再次以相同的顺序出现,而不是从最大值到最小值。
有什么建议吗?
答案 0 :(得分:4)
我已将您的信息更新为使用实际的javascript字符串,但除此之外。您的percent属性是字符串,而不是数字,因此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>
答案 1 :(得分: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)