Created
March 20, 2017 17:35
-
-
Save kishorpawar/59a299f9f78905e8c8ae67ecd9b1a6f7 to your computer and use it in GitHub Desktop.
Sorting array of objects in javascript
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
/* | |
* Using and overriding array's sort function | |
*/ | |
var sort_by_age = function(arr, key, order="asc") | |
{ | |
return arr.sort(function(elem, elem2){ | |
result = (elem[key] < elem2[key]) ? -1 : (elem[key] > elem2[key] ? 1 : 0 ); | |
if(order == "asc") | |
return result; | |
else if(order == "desc") | |
return result * -1; | |
else | |
throw "order can be either 'asc' or 'desc'." | |
}); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment