Last active
May 17, 2021 01:54
-
-
Save hollygood/5644d3c235b6481ae0c4850e9ba17e21 to your computer and use it in GitHub Desktop.
JS Arrays || Objects Tricks
This file contains hidden or 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
| // 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