Last active
June 12, 2018 08:32
-
-
Save cwoodley/9b2ca8f84526c15adda7ab5f009f71e4 to your computer and use it in GitHub Desktop.
Array and Object Manipulation
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
| const games = [ | |
| { title: 'halo', year: '2001' }, | |
| { title: 'metroid', year: '1986' }, | |
| { title: 'contra', year: '1987' }, | |
| { title: 'overwatch', year: '2016' }, | |
| { title: 'uncharted', year: '2007' } | |
| ] | |
| // how do we list these by year? | |
| // 1. declare an empty array to use as our 'scratch-pad' | |
| let sortableGames = [] | |
| // 2. for each item in the list of games, grab the title and year then push it into our empty array | |
| games.forEach(game => { | |
| sortableGames.push([game.title, game.year]) | |
| }) | |
| // 3. declare a function to perform the comparison between year values | |
| // gameA[0] = title, gameA[1] = year | |
| function compareYear(gameA, gameB) { | |
| return gameA[1] - gameB[1] | |
| } | |
| // 4. declare a new variable containing our results | |
| const sortedGames = sortableGames.sort(compareYear) | |
| // 5. convert the sorted items back into objects | |
| let orderedGames = [] | |
| sortedGames.forEach(game => { | |
| orderedGames.push({ title: game[0], year: game[1] }) | |
| }) | |
| // Log the results | |
| console.log(orderedGames) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment