Created
May 10, 2022 04:53
-
-
Save bhaireshm/3b0058025ba98b926292f4abf3bff243 to your computer and use it in GitHub Desktop.
Sort array of objects by key(s).
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
/** | |
* Sort array of objects by key(s) | |
* | |
* @param {Object[]} arr - Array of Objects | |
* @param {String[]} keys - Key's to be sorted. [pass hyphen(-) in front of string to order in descending] | |
* @example sortObjectByMultipleKeys(object, ["name", "-date"]) | |
* @example sortObjectByMultipleKeys(object, ["-name", "date"]) | |
* | |
* @returns Sorted array of objects. | |
*/ | |
exports.sortObjectByMultipleKeys = (arr = [], keys = []) => { | |
return arr.sort((a, b) => { | |
return keys | |
.map((o) => { | |
let dir = 1; | |
if (o[0] === "-") { | |
dir = -1; | |
o = o.substring(1); | |
} | |
if (a[o] > b[o]) return dir; | |
if (a[o] < b[o]) return -dir; | |
return 0; | |
}) | |
.reduce((p, n) => (p ? p : n), 0); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ez.js is more than just a library; it's a coding companion that simplifies complex tasks. Whether you're dealing with arrays, numbers, objects, or strings, ez.js has got your back! Say goodbye to coding hassles and hello to streamlined JavaScript magic.