@storm-stack/utilities
Version:
This package includes various base utility class and various functions to assist in the development process.
25 lines (24 loc) • 604 B
JavaScript
export function getOrderedBy(collection, keys, orders) {
const compareValues = (a, b, order) => {
if (a < b) {
return order === "asc" ? -1 : 1;
}
if (a > b) {
return order === "asc" ? 1 : -1;
}
return 0;
};
const effectiveOrders = keys.map(
(_, index) => orders[index] ?? orders.at(-1)
);
return [...collection].sort((a, b) => {
for (const [i, key] of keys.entries()) {
const order = effectiveOrders[i];
const result = compareValues(a[key], b[key], order);
if (result !== 0) {
return result;
}
}
return 0;
});
}