-1

How to sort ascending in the desired format? Given below is the shiftdata and desired output

 //data is in the given below format
   shiftdata = [
        { 'Name': 'A', 'Data': '57.6' },
         { 'Name': 'B', 'Data': '-10.6' },
        { 'Name': 'C', 'Data': '50.6' },
        { 'Name': 'D', 'Data': '-5.6' },
      ];

I want to convert it in sort ascending order like(Desired output)
 shiftdata = [
       { 'Name': 'B', 'Data': '-10.6' },
       { 'Name': 'D', 'Data': '-5.6' },
       { 'Name': 'C', 'Data': '50.6' },
        { 'Name': 'A', 'Data': '57.6' },
      ];

Question2: Sort ascending the shiftdata, leaving shiftdata[0] and shiftdata[last] as it is and sort ascend inside.

3 Answers3

1

You can use the sort function

shiftdata = shiftdata
    .sort((a,b) => a.Data > b.Data ? 1 : (a.Data < b.Data ? -1 : 0 ));
Titian Cernicova-Dragomir
  • 196,102
  • 20
  • 333
  • 303
1

Data sorting in an array in angular2

Just like you would do it normally in vanilla js

shiftdata.sort( function(a,b){ return a.Data - b.Data });
console.log( shiftdata ); //sorted array
gurvinder372
  • 64,240
  • 8
  • 67
  • 88
0

You can use the sort javascript method to sort your data. This function accepts a comparation function to sort your data as you want.

In your case it would be:

var sortShiftdata = shiftdata.sort(function(a, b){
    return a.Data-b.Data
})

If you use ES6 you can use the arrow functions:

const sortShifdata = shiftdata.sort((a, b) => a.Data - b.Data)
console.log(sortShifdata)