简体   繁体   English

Loadash降序降序在JavaScript中不起作用(React Native)

[英]Loadash orderby descending not working in JavaScript (React Native)

I am getting array from server like below. 我从下面的服务器获取数组。

[
  {
    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'
  }
]

From above list, I have to show Maximum percentage values to lowest values. 从上面的列表中,我必须将“最大百分比值”显示为“最低值”。

So, I tried like below. 所以,我尝试如下。

if (jsonData) {
      const sortedArray = orderBy(
        jsonData,
        ['percentage'],
        ['desc']
      );
      console.log('sortedArray is ', sortedArray);

}

Its coming again same order, Not ordering from maximum values to lowest values. 它再次以相同的顺序出现,而不是从最大值到最小值。

Any suggestions? 有什么建议么?

I have updated your post to use actual javascript strings, but beside that. 我已将您的帖子更新为使用实际的javascript字符串,但除此之外。 Your percentage property is a string and not a number so the ordering is done differently by lodash. 您的percent属性是字符串,而不是数字,因此lodash的排序方式有所不同。 Either ensure the percentages come back as proper numbers from the server or map them to a number. 确保百分比以正确的数字从服务器返回,或者将它们映射到数字。

 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> 

You can simply use sort function of native JS 您可以简单地使用本机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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM