[英]Loadash orderby descending not working in 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字符串,但除此之外。 您的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>
您可以簡單地使用本機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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.