Skip to content

Instantly share code, notes, and snippets.

@agm1984
Created November 19, 2018 19:08
Show Gist options
  • Save agm1984/a1286afdb7c876f007d4a0a7e0ef154c to your computer and use it in GitHub Desktop.
Save agm1984/a1286afdb7c876f007d4a0a7e0ef154c to your computer and use it in GitHub Desktop.
JavaScript Sort algorithm
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