JavaScript function that returns a sorted array of objects ordered by properties and orders.
/**
* order By
*
* Returns a sorted array of objects ordered by properties and orders.
*
* Returns a sorted array of objects ordered by properties and orders.
* Uses `Array.prototype.sort()`, `Array.prototype.reduce()` on the props array
* with a default value of 0, use array destructuring to swap the properties
* position depending on the order passed. If no `orders` array is passed it
* sort by `'asc'` by default.
*
* @param {Array} arr
* @param {Array} props
* @param {Array} orders
* @return {Array} A sorted array of objects ordered by properties and orders.
*/
const orderBy = (arr, props, orders) =>
[...arr].sort((a, b) =>
props.reduce((acc, prop, i) => {
if (acc === 0) {
const [p1, p2] =
orders && orders[i] === "desc"
? [b[prop], a[prop]]
: [a[prop], b[prop]];
acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;
}
return acc;
}, 0)
);
//
// Compiled (ES2015)
"use strict";
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
var orderBy = function (arr, props, orders) {
return __spreadArrays(arr).sort(function (a, b) {
return props.reduce(function (acc, prop, i) {
if (acc === 0) {
var _a = orders && orders[i] === "desc"
? [b[prop], a[prop]]
: [a[prop], b[prop]], p1 = _a[0], p2 = _a[1];
acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;
}
return acc;
}, 0);
});
};
// --------------------------------------------------
// Example Usage
// --------------------------------------------------
const users = [
{ name: "fred", age: 48 },
{ name: "barney", age: 36 },
{ name: "fred", age: 40 }
];
orderBy(users, ["name", "age"], ["asc", "desc"]); // [{name: 'barney', age: 36}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]
orderBy(users, ["name", "age"]); // [{name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]