-
-
Save ravivit9/c3f42bb9772a75bfb858 to your computer and use it in GitHub Desktop.
JS: Sort a JavaScript object by key in alphabetical order case insensitive. Thanks to Arne Martin Aurlien and Ivan Krechetov for inspiration. #snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment