javascriptsortingdescendant

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?


Solution

  • You can simply use sort function of native JS

    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)