Created
April 20, 2011 00:30
-
-
Save xjamundx/930065 to your computer and use it in GitHub Desktop.
fancy object sort example
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
var locations = { | |
seattle: {reviews:[{title:"c"}]}, | |
portland: {reviews:[{title:"v"}]}, | |
provo: {reviews:[{title:"c"}]}, | |
}; | |
sort(locations).by("title").on("reviews"); | |
function sort(obj) { | |
sort.obj = obj; | |
sort.by = function(field) { | |
sort.field = field; | |
return sort; | |
} | |
sort.on = function(arrayKey) { | |
for (var i in sort.obj) { | |
obj[i][arrayKey].sort(sortBy(sort.field)); | |
}; | |
return sort; | |
} | |
return sort; | |
} | |
function sortBy(field) { | |
if (!sortBy.fields) sortBy.fields = {}; | |
if (sortBy.fields[field]) return sortBy.fields[field]; | |
sortBy.fields[field] = function(a, b) { | |
a = a[field].toLowerCase() | |
b = b[field].toLowerCase(); | |
if (a < b) return -1; | |
if (a > b) return 1; | |
return 0; | |
} | |
return sortBy.fields[field]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment