Sort a sorted array of objects based on the increasing order of another attribute

I have an array of objects that have TechType and ProductName attributes. This array is already sorted by TechType (not necessarily in alphabetical order); now in this sorted array it should be sorted in 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", } ]; 

A sorted array must 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", } ]; 
+5
source share
1 answer

This is somewhat due to stable sorting. A typical way to ensure stable sorting is to add ancillary data to sort by if the elements are found to be the same.

I am doing this here using two map operations similar to what you would use for the Schwartz transform; auxiliary data is used only if technical types do not match between two elements.

To demonstrate the correct behavior, I moved the elements around so that the types of technologies are ordered in the 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)); 
+2
source

All Articles