Skip to content

Instantly share code, notes, and snippets.

@bhaireshm
Created May 10, 2022 04:53
Show Gist options
  • Save bhaireshm/3b0058025ba98b926292f4abf3bff243 to your computer and use it in GitHub Desktop.
Save bhaireshm/3b0058025ba98b926292f4abf3bff243 to your computer and use it in GitHub Desktop.
Sort array of objects by key(s).
/**
* 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);
});
};
@bhaireshm
Copy link
Author

bhaireshm commented Feb 24, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment