Last active
February 26, 2018 21:03
-
-
Save adamculpepper/a46afdb42affbe90f351a27952c0c6cb to your computer and use it in GitHub Desktop.
Sort a JavaScript array that has key values
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
Array.prototype.keySort = function(key, sort){ | |
this.sort(function(a, b) { | |
if (sort == 'desc') { | |
var result = (a[key] < b[key]); | |
} else if (sort == 'asc') { | |
var result = (a[key] > b[key]); | |
} | |
return result ? 1 : -1; | |
}); | |
return this; | |
} | |
dataArray.keySort('OrderID', 'asc'); //USAGE | |
dataArray.keySort('OrderDate', 'desc'); //USAGE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment