Created
June 20, 2011 23:32
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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