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.
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 }
];
// sort by prop1 then by prop3 then by prop4:
var sortedItems = sortByThenBy(items, ["prop1", "prop3", "prop4"]);
// sort by prop1 then by prop3:
var sortedItems = sortByThenBy(items, ["prop1", "prop3"]);
Thanks for all great answers. For information, I discovered that a recursive approach is also an alternative solution
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.
You could iterate the keys and use
Array#some
for getting the order value.This proposal works with a short circuit, if a delta is truthy (
!== 0
), then the iteration breaks and the delta is returned to the sort callback.Do it using
Array#sort
andArray#reduce
methods.I think you can do as follows;