Created
November 19, 2018 19:08
-
-
Save agm1984/a1286afdb7c876f007d4a0a7e0ef154c to your computer and use it in GitHub Desktop.
JavaScript Sort algorithm
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
const data = [ | |
{ first: 'David', last: 'Goldstein', age: 92 }, | |
{ first: 'Tom', last: 'Stamper', age: 23 }, | |
{ first: 'Sally', last: 'Brunswick', age: 76 }, | |
{ first: 'Steve', last: 'Henderson', age: 37 }, | |
{ first: 'Mark', last: 'Chopper', age: 75 }, | |
{ first: 'Lucy', last: 'Steel', age: 29 }, | |
] | |
// localeCompare is a String prototype: | |
// template literals are used to convert Numbers to Strings rather than `String()` or `'' + num` | |
// due to performance on large collections | |
// `String.toString()` is not used because it doesn't handle falsy values | |
// falsy values should really be trimmed, but they are not in this gist | |
const sort = ({ data, field, desc }) => { | |
if (desc) { | |
return data.sort((a, b) => `${b[field]}`.localeCompare(`${a[field]}`)) | |
} | |
// if desc is omitted, we will sort by ascending | |
return data.sort((a, b) => `${a[field]}`.localeCompare(`${b[field]}`)) | |
} | |
console.log( | |
sort({ data, field: 'age', desc: true }) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment