×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Added: Sep 24, 2018 2:22 PM
Views: 3438
  1. /**
  2.  * Sort object properties (only own properties will be sorted).
  3.  * @param {object} obj object to sort properties
  4.  * @param {bool} isNumericSort true - sort object properties as numeric value, false - sort as string value.
  5.  * @returns {Array} array of items in [[key,value],[key,value],...] format.
  6.  */
  7. function sortProperties(obj, isNumericSort) {
  8.         isNumericSort = isNumericSort || false; // by default text sort
  9.         let sortable = [];
  10.         for (let key in obj) {
  11.                 if(obj.hasOwnProperty(key)) {
  12.                         sortable.push([key, obj[key]]);
  13.                 }
  14.         }
  15.         if (isNumericSort) {
  16.                 sortable.sort(function(a, b) {
  17.                         return a[1]-b[1];
  18.                 });
  19.         } else {
  20.                 sortable.sort(function(a, b) {
  21.                         let x = a[1].toLowerCase(),
  22.                             y = b[1].toLowerCase();
  23.  
  24.                         return x < y ? -1 : x > y ? 1 : 0;
  25.                 });
  26.         }
  27.  
  28.         // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
  29.         return sortable;
  30. }