我正在从服务器获取如下所示的数组。
[
{
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>
你可以简单地使用本机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)