How to write a generic sorting function in the style orderBy thenBy that sort an array by a list of properties provided as an array.
Do it using Array#sort
and Array#reduce
methods.
function sortByThenBy(arr, props) {
// apply custom sort function on array
return arr.sort(function(a, b) {
// generate compare function return value by
// iterating over the properties array
return props.reduce(function(bool, k) {
// if previous compare result is `0` then compare
// with the next property value and return result
return bool || (a[k] - b[k]);
// set initial value as 0
}, 0);
})
}
var items = [{
name: "AA",
prop1: 12,
prop2: 13,
prop3: 5,
prop4: 22
}, {
name: "AA",
prop1: 12,
prop2: 13,
prop3: 6,
prop4: 23
}, {
name: "AA",
prop1: 12,
prop2: 14,
prop3: 5,
prop4: 23
}, {
name: "AA",
prop1: 11,
prop2: 13,
prop3: 5,
prop4: 22
}, {
name: "AA",
prop1: 10,
prop2: 13,
prop3: 9,
prop4: 21
}];
console.log(sortByThenBy(items, ["prop1", "prop3", "prop4"]));
console.log(sortByThenBy(items, ["prop1", "prop3"]));
console.log(sortByThenBy(items, ["prop2", "prop3"]));
function sortByThenBy(arr, props) {
return arr.sort(function(a, b) {
return props.reduce(function(bool, k) {
return bool || (a[k] - b[k]);
}, 0);
})
}
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}