-3

I have this simple JSON table where the elements needs to be sorted in alpabetical order by value and the other alpabetical order by name. Could someone give me and example how would i do it so i can understand it?

{

  "sortingTask": [

      {"sortAlpabeticallyByValue": [

      {"string":"äää"},

      {"string":"bee"},

      {"string":"aaa"},

      {"string":"öoöo"},

      {"string":"OöOö"},   

  ]},

      {"sortAlpabeticallyByName": [

      {"stringB":"testi1"},

      {"stringÄ":"testi2"},

      {"stringA":"testi3"}

  ]},

  {"sortAlpabetically": [

      "äää","bee","baa"

  ]}

  ]

}

1 Answers1

0

You need to implement custom sort method using switch case. For comparison between two words you can use localeCompare

var data = { "sortingTask": [ {"sortAlpabeticallyByValue": [ {"string":"äää"}, {"string":"bee"}, {"string":"aaa"}, {"string":"öoöo"}, {"string":"OöOö"}, ]}, {"sortAlpabeticallyByName": [{"stringB":"testi1"}, {"stringÄ":"testi2"}, {"stringA":"testi3"} ]}, {"sortAlpabetically":[ "äää","bee","baa" ]}]};

data.sortingTask.forEach(function(obj){
  Object.keys(obj).forEach(function(k){
    switch(k){
      case 'sortAlpabeticallyByValue' :
        obj[k].sort(function(a,b){
          return a.string.localeCompare(b.string, undefined, { sensitivity: 'variant' });
        });
        break;
       case 'sortAlpabetically':
        obj[k].sort(function(a,b){
          return a.localeCompare(b, undefined, {sensitivity: 'variant'});
        });
        break;
       case 'sortAlpabeticallyByName':
        obj[k].sort(function(a,b){
          return Object.keys(a)[0].localeCompare(Object.keys(b)[0]);
        });
        break;
    }
  });
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51