Last active
September 5, 2017 05:15
-
-
Save finom/727b971ca5d62d25a228 to your computer and use it in GitHub Desktop.
Orderby JavaScript function
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 orderBy = function(arr, keys, orders) { | |
var defaultOrder = 'asc', | |
newArr, | |
length, | |
i, | |
commonOrder; | |
if ('length' in arr && typeof arr == 'object') { | |
if (!(orders instanceof Array)) { | |
commonOrder = orders || defaultOrder; | |
} | |
length = arr.length; | |
newArr = Array(length); | |
for(i = 0; i < length; i++) { | |
newArr = arr[i]; | |
} | |
if(!keys) return newArr; | |
keys = keys instanceof Array ? keys : [keys]; | |
return newArr.sort(function(a, b) { | |
var length = keys.length, | |
i, | |
order, | |
key; | |
if(a && b) { | |
for (i = 0; i < length; i++) { | |
key = keys[i]; | |
order = (commonOrder || orders[i] || defaultOrder) == 'asc' ? -1 : 1; | |
if (a[key] > b[key]) { | |
return -order; | |
} else if (a[key] < b[key]) { | |
return order; | |
} | |
} | |
} | |
return 0; | |
}); | |
} else { | |
return []; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This looks great. Please can you provide a quick example of how to use it?