Last active
August 29, 2015 14:23
-
-
Save robinweser/f8c6b52ddec3bf197e3a to your computer and use it in GitHub Desktop.
Adds a sorting algorithm to objects to sort by property or value
This file contains 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
/* | |
Returns an alphabethic or value-base ascending/descending sorted Object (child objects sorted if recursive) | |
*/ | |
Object.prototype.sort = function(recursive, direction, caseSensitive, sortByValue) { | |
var dir = (direction ? direction : "ASC"); | |
var me = this; | |
var tempArray = []; | |
/* | |
Sorting function for value-based (sortByValue) sorting | |
*/ | |
var sortArrayByValue = function (a, b) { | |
var left = me[a]; | |
var right = me[b]; | |
if (!caseSensitive) { | |
left = (typeof left == "string" ? left.toLowerCase() : left); | |
right = (typeof right == "string" ? right.toLowerCase() : right); | |
} | |
return ((left < right) ? -1 : ((left > right) ? 1 : 0)); | |
} | |
for (var item in this) { | |
if (typeof this[item] == "object" && this[item] != null && recursive) { | |
/* | |
Recursively sort child objects | |
*/ | |
this[item] = this[item].sort(recursive, dir, caseSensitive, sortByValue); | |
} | |
if (this.hasOwnProperty(item)) { | |
if (!caseSensitive) { | |
item = (item['toLowerCase'] ? item.toLowerCase() : item); | |
} | |
tempArray.push(item); | |
} | |
} | |
if (sortByValue) { | |
tempArray.sort(sortArrayByValue); | |
} else { | |
tempArray.sort(); | |
} | |
var tempObject = {}; | |
if (dir == "DESC") { | |
tempArray.reverse(); | |
} | |
/* | |
new Object from Array | |
*/ | |
for (var i = 0; i < tempArray.length; i++) { | |
tempObject[tempArray[i]] = this[tempArray[i]]; | |
} | |
return tempObject; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment