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.
try this solution.I'm creating sequence with data used in comparision like data1|0000NumberData2|data3
. After that using native sort JS function to compare this sequence.
To avoid string comparision problem with numbers - zero padding used 000000345
So you can specify fields to use and fields sequence.
var items = [{ name: "AA", prop1 : 12, prop2: 13, prop3: 5, prop4: 22 },
{ name: "AA", prop1 : 2, prop2: 13, prop3: 6, prop4: 23 },
{ name: "AB", 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 }];
// sort by prop1 then by prop3 then by prop4:
var sortedItems = sortByThenBy(items, ["prop1", "prop3", "prop4"]);
console.log(sortedItems);
// sort by prop1 then by prop3:
var sortedItems = sortByThenBy(items, ["prop1", "prop3"]);
console.log(sortedItems);
function sortByThenBy(items, props) {
return items.sort(function(a, b) {
var a_path = $.map(props, function(item) {
var ret = a[item];
return isNumber(ret) ? pad(ret, 10) : ret;
}).join('|');
var b_path = $.map(props, function(item) {
var ret = b[item];
return isNumber(ret) ? pad(ret, 10) : ret;
}).join('|');
return a_path > b_path ? 1 : (a_path == b_path ? 0 : -1);
});
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function pad(n, width) {
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
}