Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Added: Sep 24, 2018 2:19 PM
Modified: Sep 24, 2018 2:25 PM
Views: 2
Sort object properties by value (values are text)
  1. /**
  2.  * Sort object properties by value (values are text)
  3.  *
  4.  * I have following object:
  5.  * var cities={10:'Tashkent', 14:'Karakalpakiya', 16:'Andijan'};
  6.  *
  7.  * I want sort it by city names, so after sort it should be:
  8.  * var cities={16:'Andijan', 14:'Karakalpakiya', 10:'Tashkent'};
  9.  *
  10.  * Example:
  11.  * var sortedCities = sortProperties(cities);
  12.  * console.log(sortedCities); // [[16, 'Andijan'], [14, 'Karakalpakiya'], [10, 'Tashkent']]
  13.  */
  14. function sortProperties(obj) {
  15.         // convert object into array
  16.         let sortable = [];
  17.         for(let key in obj) {
  18.                 if(obj.hasOwnProperty(key)) {
  19.                         // each item is an array in format [key, value]
  20.                         sortable.push([key, obj[key]]);
  21.                 }
  22.         }
  23.        
  24.         // sort items by value
  25.         sortable.sort(function(a, b) {
  26.                 let x = a[1].toLowerCase(),
  27.                     y = b[1].toLowerCase();
  28.  
  29.                 return x < y ? -1 : x > y ? 1 : 0;
  30.         });
  31.  
  32.         // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
  33.         return sortable;
  34. }