Skip to content

Instantly share code, notes, and snippets.

@d1820
Last active March 15, 2017 02:37
Show Gist options
  • Save d1820/991237263d24a9fcac6ef8a0131b97bb to your computer and use it in GitHub Desktop.
Save d1820/991237263d24a9fcac6ef8a0131b97bb to your computer and use it in GitHub Desktop.
Cool multiple sort function found online, that also handles reverse sorting.
generateSortFn(props) {
return function (a, b) {
for (var i = 0; i < props.length; i++) {
var prop = props[i];
var name = prop.name;
var reverse = prop.reverse;
if (a[name] < b[name])
return reverse ? 1 : -1;
if (a[name] > b[name])
return reverse ? -1 : 1;
}
return 0;
};
}
//LODASH Version - this handles nested objects
import * as _ from 'lodash';
export class ArrayHelper {
public static multisort(array, props): any {
let sortfunc = function (a, b) {
for (var i = 0; i < props.length; i++) {
let prop = props[i];
let name = prop.name;
let reverse = prop.reverse;
let aVal = _.get(a, name);
let bVal = _.get(b, name)
if (aVal < bVal)
return reverse ? 1 : -1;
if (aVal > bVal)
return reverse ? -1 : 1;
}
return 0;
};
array.sort(sortfunc);
}
}
//Example
//let fn = this.generateSortFn([{ name: 'sortWeight', reverse: true }, { name: 'title'}]);
// arr.sort(fn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment