// Normal way
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 );
}
// Better way
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'));
Last active
May 17, 2021 01:54
-
-
Save hollygood/5644d3c235b6481ae0c4850e9ba17e21 to your computer and use it in GitHub Desktop.
JS Arrays || Objects Tricks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment