Suggest a feature
×

Welcome to TagMyCode

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