Skip to content

Instantly share code, notes, and snippets.

@MetaThis
Created June 20, 2011 23:32
Show Gist options
  • Save MetaThis/1036874 to your computer and use it in GitHub Desktop.
Save MetaThis/1036874 to your computer and use it in GitHub Desktop.
JS Nested Sort Example (with comparator function factory for composing arbitrary nesting levels)
//some sample data for the example
var people = [ {firstName: "Bob", lastName: "Barker", age: 100}, {firstName: "John", lastName: "Smith", age: 40}, {firstName: "Sam", lastName: "Adams", age: 42}, {firstName: "John", lastName: "Adams", age: 42}, {firstName: "Bernard", lastName: "Adams", age: 42}, {firstName: "Adam", lastName: "Adams", age: 42} ];
//generalized comparator function factory enabling composition with nested comparators
var comparatorComposer = function(compareBy, nextComparator) {
var comparator = function(a, b) {
return ((a[compareBy] < b[compareBy]) ? -1 : ((a[compareBy] > b[compareBy]) ? 1 : (nextComparator ? nextComparator(a, b) : 0)));
};
return comparator;
};
//run each of these pairs of lines in the Chrome console to see the output
var compareByFirstName = comparatorComposer("firstName");
people.sort(compareByFirstName);
var compareByLastNameAndFirstName = comparatorComposer("lastName", compareByFirstName);
people.sort(compareByLastNameAndFirstName);
var compareByAgeAndLastNameAndFirstName = comparatorComposer("age", compareByLastNameAndFirstName);
people.sort(compareByAgeAndLastNameAndFirstName);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment