typedash
Version:
modern, type-safe collection of utility functions
29 lines (27 loc) • 1.24 kB
JavaScript
import { t as castArray } from "./castArray-BlJadbg0.js";
//#region src/functions/orderBy/orderBy.ts
/**
* Sorts an array of objects by one or more properties, in ascending or descending order.
* @param array The array of objects to sort.
* @param iterators The property or properties to sort by. Can be a key of `TValue` or a function that returns a comparable value.
* @param orders The order or orders to sort by. Can be "asc" or "desc". Defaults to "asc".
* @returns A new array of objects sorted by the specified properties and orders.
*/
function orderBy(array, iterators, orders) {
if (array == null) return [];
const normalizedIteratees = castArray(iterators).map((iteratee) => typeof iteratee === "function" ? iteratee : (value) => value[iteratee]);
const normalizedOrders = castArray(orders);
return [...array].sort((a, b) => {
for (const [index, iteratee] of normalizedIteratees.entries()) {
const order = (normalizedOrders[index] ?? "asc") === "desc" ? -1 : 1;
const aValue = iteratee(a);
const bValue = iteratee(b);
if (aValue < bValue) return -1 * order;
if (aValue > bValue) return 1 * order;
}
return 0;
});
}
//#endregion
export { orderBy as t };
//# sourceMappingURL=orderBy-B4PpVAjN.js.map