Skip to content

Instantly share code, notes, and snippets.

@CFJSGeek

CFJSGeek/sortObj.js

Last active Jul 22, 2020
Embed
What would you like to do?
JS: Sort a JavaScript object by key in alphabetical order case insensitive. Thanks to Arne Martin Aurlien and Ivan Krechetov for inspiration. #snippet
/**
* Sort JavaScript Object
* CF Webtools : Chris Tierney
* obj = object to sort
* order = 'asc' or 'desc'
*/
function sortObj( obj, order ) {
"use strict";
var key,
tempArry = [],
i,
tempObj = {};
for ( key in obj ) {
tempArry.push(key);
}
tempArry.sort(
function(a, b) {
return a.toLowerCase().localeCompare( b.toLowerCase() );
}
);
if( order === 'desc' ) {
for ( i = tempArry.length - 1; i >= 0; i-- ) {
tempObj[ tempArry[i] ] = obj[ tempArry[i] ];
}
} else {
for ( i = 0; i < tempArry.length; i++ ) {
tempObj[ tempArry[i] ] = obj[ tempArry[i] ];
}
}
return tempObj;
}
@PrincessRTFM

This comment has been minimized.

Copy link

@PrincessRTFM PrincessRTFM commented May 24, 2016

Why not just reverse tempArry before the final block instead of copy/pasting the for block like that?

@farskid

This comment has been minimized.

Copy link

@farskid farskid commented Jan 29, 2018

You can write it in a more functional way.
https://gist.github.com/farskid/b1c128639cd42e44734282e2d9e3beb2

function sortObjKeysAlphabetically(obj) {
  return Object.keys(obj).sort((a,b) => a > b).reduce((result, key) => {
    result[key] = obj[key];
	return result;
  }, {});
}
function sortObj(obj, order) {
  switch (order) {
    case 'asc':
      return sortObjKeysAlphabetically(obj);
      break;
    case 'desc':
      return sortObjKeysAlphabetically(obj).reverse();
      break;
    default:
      throw Error('invalid order');
  }
}
@humanismusic

This comment has been minimized.

Copy link

@humanismusic humanismusic commented Mar 6, 2018

@farksid that didn't work perfectly. This seems to do it:

function sortObjKeysAlphabetically(obj) {
  var ordered = {};
 Object.keys(obj).sort().forEach(function(key) {
   ordered[key] = obj[key];
 });
return ordered;
}

var sortedObj = sortObjKeysAlphabetically(unorderedObj);
@janhesters

This comment has been minimized.

Copy link

@janhesters janhesters commented Oct 17, 2018

This code sorts objects deeply and will also handle arrays:

const alphaSort = (object: any): object => {
  if (object !== null && typeof object === "object") {
    return Object.keys(object)
      .sort((a, b) => sortByAlphabet(a.toLowerCase(), b.toLowerCase()))
      .reduce((result: object, key: string) => {
        result[key] = object[key];
        if (Array.isArray(result[key])) {
          result[key] = result[key].map((obj: any) => alphaSort(obj));
        }
        return result;
      }, {});
  } else if (Array.isArray(object)) {
    return object.map(obj => alphaSort(obj));
  } else {
    return object;
  }
};
@maksof-kashif

This comment has been minimized.

Copy link

@maksof-kashif maksof-kashif commented Mar 20, 2019

// function
sortArr(a, b) {
var textA = a.keyName.toUpperCase();
var textB = b.keyName.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
}

// calling function (here array is your array item)

array.sort(this.sortArr);

@shwao

This comment has been minimized.

Copy link

@shwao shwao commented Jul 22, 2020

const sortObjKeysAlphabetically = (obj) => Object.fromEntries(Object.entries(obj).sort());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.