Created
June 19, 2018 20:39
-
-
Save JokingChicken/5eb1ea1dbd30b1b294d347bd44dcb22c to your computer and use it in GitHub Desktop.
sort a object by a objectkey
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
/* | |
* creator: Danj (https://github.com/DanBrothers) | |
* description: sort a array by key values | |
* license: MIT, please link to this if you copy (thanks) | |
* | |
* usage: | |
//returns a sorted array | |
sortby(array, { | |
desc: true, | |
prop: "name", | |
parser: functon(item) { | |
return new | |
} | |
}); | |
*/ | |
function sortby(array, cfg) { | |
if (!(array instanceof Array && array.length)) { | |
return []; | |
} | |
if (!(cfg instanceof Object)) { | |
cfg = {}; | |
} | |
if (typeof cfg.parser !== "function") { | |
cfg.parser = function (x) { return x; }; | |
} | |
var getItem = function (x) { | |
var isProp = x != null && typeof x === "object" && this.prop in x; | |
return this.parser(isProp ? x[this.prop] : x); | |
}; | |
cfg.desc = !!cfg.desc ? -1 : 1; | |
return array.sort(function (a, b) { | |
a = getItem(a); | |
b = getItem (b); | |
return cfg.desc * (a < b ? -1 : +(a > b)); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment