Skip to content

Instantly share code, notes, and snippets.

@cwoodley
Last active June 12, 2018 08:32
Show Gist options
  • Select an option

  • Save cwoodley/9b2ca8f84526c15adda7ab5f009f71e4 to your computer and use it in GitHub Desktop.

Select an option

Save cwoodley/9b2ca8f84526c15adda7ab5f009f71e4 to your computer and use it in GitHub Desktop.
Array and Object Manipulation
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