Skip to content

Instantly share code, notes, and snippets.

@hollygood
Last active May 17, 2021 01:54
Show Gist options
  • Select an option

  • Save hollygood/5644d3c235b6481ae0c4850e9ba17e21 to your computer and use it in GitHub Desktop.

Select an option

Save hollygood/5644d3c235b6481ae0c4850e9ba17e21 to your computer and use it in GitHub Desktop.
JS Arrays || Objects Tricks
// Remove repeat code
if ( this.orderBy ) {
results = this.order === 'asc' ?
results[0].sort( (a, b) => (
a[ this.orderBy ] > b[ this.orderBy ] ) ? 1 : -1 ):
results[0].sort( (a, b) => (
a[ this.orderBy ] < b[ this.orderBy ] ) ? 1 : -1 );
}
// New Approach
const inversionFactor = this.order === 'asc' ? 1 : -1;
results = results[0].sort( (a, b) =>
a[ this.orderBy ] < b[ this.orderBy ] : -1 * inversionFactor : 1 * inversionFactor
);
// this is a reusable function and can go outside of other functions
const compareBy = (prop, invert) => (a, b) => {
if (a[prop] === b[prop]) { return 0; }
return (a[prop] < b[prop] ? -1 : 1) * (invert ? -1 : 1);
};
results = results[0].sort(compareBy(this.orderBy, this.order === 'desc'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment