Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a sorted object array based on ascending order of another attribute

I have an array of objects having attributes TechType and ProductName. The given array is already sorted by TechType (not necessarily alphabetically); now within this sorted array, it has to be further sorted by ascending order based on ProductName.

var products= [
    {
        "TechType": "ADSL",
        "ProductName": " Zen ADSL Services",
            }, {
        "TechType": "ADSL",
        "ProductName": "ADSL Services",
            }, {
        "TechType": "T1",
        "ProductName": "T1-Voice",
},{
      "TechType": "T1",
        "ProductName": " Aviate T1-Voice",


 }
];

The sorted array should be

  var products= [
        {
            "TechType": "ADSL",
            "ProductName": " ADSL Services",
                }, {
            "TechType": "ADSL",
            "ProductName": "Zen ADSL Services",
                }, {
            "TechType": "T1",
            "ProductName": " Aviate T1-Voice",
    },{
          "TechType": "T1",
            "ProductName": " T1-Voice",


     }
    ];
like image 734
Sanjana Avatar asked Nov 01 '22 02:11

Sanjana


1 Answers

This is somewhat related to stable sort. The typical way to ensure a stable sort is by adding auxiliary data by which should be sorted in case items are found to be the same.

I'm doing this here using two map operations, similar to what you would use for a Schwartzian Transform; the auxiliary data is used only if the tech types don't match between two items.

To demonstrate the correct behaviour I've moved the items around so that tech types are ordered in reverse order from the question.

var products = [{
  "TechType": "T1",
  "ProductName": "T1-Voice",
},{
  "TechType": "T1",
  "ProductName": "Aviate T1-Voice",
}, {
  "TechType": "ADSL",
  "ProductName": "Zen ADSL Services",
}, {
  "TechType": "ADSL",
  "ProductName": "ADSL Services",
}];

function sortByStableProperty(array, prop, fn)
{
  // decorate
  var temp = array.map(function(item, index) {
    return [item, index];
  });
  
  temp.sort(function(a, b) {
    // sort by auxiliary data or callback function
    return a[0][prop] == b[0][prop] ? fn(a[0], b[0]) : a[1] - b[1];
  });
  
  // undecorate
  return temp.map(function(item) {
    return item[0];
  });
}

// actual sort
products = sortByStableProperty(products, 'TechType', function(a, b) {
  return a.ProductName.localeCompare(b.ProductName);
});

console.log(JSON.stringify(products));
like image 90
Ja͢ck Avatar answered Nov 12 '22 17:11

Ja͢ck