Skip to content

Instantly share code, notes, and snippets.

@ricalamino
Forked from manix/sample.js
Last active August 6, 2018 14:48
Show Gist options
  • Save ricalamino/533df58548080dbde013278467735c24 to your computer and use it in GitHub Desktop.
Save ricalamino/533df58548080dbde013278467735c24 to your computer and use it in GitHub Desktop.
Improved "fieldSorter" - usage( arrayOfObjects.sort(fieldSorter(['-price', 'orderId'])); )
function fieldSorterOptimized(fields) {
var dir = [], i, l = fields.length;
fields = fields.map(function(o, i) {
if (o[0] === "-") {
dir[i] = -1;
o = o.substring(1);
} else {
dir[i] = 1;
}
return o;
});
return function (a, b) {
for (i = 0; i < l; i++) {
var o = fields[i];
if (a[o] > b[o]) return dir[i];
if (a[o] < b[o]) return -(dir[i]);
}
return 0;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment