Flat object compare
Creates a comparison function for objects than can be sent as an argument to Array.prototype.sort().
Installation
$ npm install --save flat-object-compare
Example (basic)
var comparer = ;var comp = comparer; // ==> 1// 'John' == 'John' so the comparison cascades to the lastName fields where 'Smith' > 'Doe'
The comparison function in created by calling the objectComparison
function with a string array containing the desired field names:
var comparer = ;var comp = comparer;
If the objects are stored in an array a, then a.sort(comp) would produce an array sorted in the correct order, similar to ORDER BY in SQL or the sort functionality in Excel.
To flip the sort order, pass a -1 (or any negative number as a second argument)
var comp = comparer; // flips sort order
Example (with sort())
var comparer = ;var comp = comparer;var data = lastName: 'Johannsen' firstName: 'Becky' registrationDate: '2017-03-01' instrument: 'piano' lastName: "O'Connor" firstName: 'Sam' registrationDate: '2016-06-01' instrument: 'cello' lastName: "Johannsen" firstName: 'Paul' registrationDate: '2017-03-17' instrument: 'violin' lastName: "Johannsen" firstName: 'Paul' registrationDate: '2017-03-22' instrument: 'triangle' }; data;/*data is now [ { lastName: 'Johannsen', firstName: 'Becky', registrationDate: '2017-03-01', instrument: 'piano' }, { lastName: "Johannsen", firstName: 'Paul', registrationDate: '2017-03-17', instrument: 'violin' }, { lastName: "Johannsen", firstName: 'Paul', registrationDate: '2017-03-22', instrument: 'triangle' }, { lastName: "O'Connor", firstName: 'Sam', registrationDate: new Date('2016-06-01'), instrument: 'cello' }, ];*/