Manzer Ahmad Hashmi
Manzer Ahmad Hashmi

Reputation: 1

Data Sorting in an array keeping first and last element position fixed in angular2

Sort ascending and decending order in the desired format? Given below is the shdata and desired output?

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

I want to convert it in sort ascending order and descending order like(Desired output).

Note: shdata[0] and shdata[last] should retain their position as it is, the sorting should be in between them.

     shdata = [
            { 'Name': 'A', 'Data': '57.6' },
             { 'Name': 'C', 'Data': '-50.6' },
            { 'Name': 'B', 'Data': '-10.6' },
            { 'Name': 'F', 'Data': '0.6' },
            { 'Name': 'E', 'Data': '10.6' },
            { 'Name': 'D', 'Data': '50.6' },   
            { 'Name': 'G', 'Data': '-5.6' },
          ];

Upvotes: 0

Views: 1090

Answers (2)

Julio Ojeda
Julio Ojeda

Reputation: 817

Here is a simple solution to this problem.

    shdata = [
        { 'Name': 'A', 'Data': '57.6' },
        { 'Name': 'B', 'Data': '-10.6' },
        { 'Name': 'C', 'Data': '-50.6' },
        { 'Name': 'D', 'Data': '50.6' },
        { 'Name': 'E', 'Data': '10.6' },
        { 'Name': 'F', 'Data': '0.6' },
        { 'Name': 'G', 'Data': '-5.6' },
        ];

    var first = shdata.shift();
    var last = shdata.pop();

    shdata.sort( function (a,b) {
      if( parseFloat(a.Data) > parseFloat(b.Data)){
        return 1;
      }else {
        return 0;
      }
    });

    shdata.splice(0,0,first);
    shdata.push(last);

Upvotes: 4

Jason L
Jason L

Reputation: 1822

Seems like the simplest idea would be to slice the array into the subset that you want to sort (second to second-to-last indices would be 1 to length - 1), sort that subset, and then recreate the array.

Since you're trying to sort objects, you'll have to define a custom sort function. Also, since it seems like your Data property is a number but stored as a string, you'll have to do the conversion in the sort function. Alternately, store numbers instead of strings. Once you have your subset, you can call the subset's sort like so:

// sort ascending
subset.sort(function(a, b) {
    return parseFloat(a.Data) - parseFloat(b.Data);
});

After that, it's a simple matter of putting your pieces together.

var result = [shdata[0]];
result = result.concat(subset);
result.push(shdata[shdata.length - 1]);

Upvotes: 2

Related Questions