Skip to content

Instantly share code, notes, and snippets.

@sleeptil3
Last active September 20, 2021 18:29
Show Gist options
  • Save sleeptil3/f47fc8aeefcfc32082437510b13550ca to your computer and use it in GitHub Desktop.
Save sleeptil3/f47fc8aeefcfc32082437510b13550ca to your computer and use it in GitHub Desktop.
Array Reduce Example
// Prompt: take an array called "cards" that is a hand in a card game populated with card Objects and return an Object that sorts the cards according to suit (i.e. the key will be the suit name and the value will be an array of face values of that suit)
/*
- On line 20, you can see I'm setting the default value of the accumulator to an empty Object {} and naming the argument "suits" for clarity
- This is because the default value of the accumulator is 0, but since I want the reducer to return an Object, you indicate that here to override the default behavior.
- The conditional on line 17 checks if the current suit already exists in the suits Object, and if not, creates an empty array to receive it
*/
const card1 = { value: "9", suit: "hearts" }
const card2 = { value: "K", suit: "hearts" }
const card3 = { value: "J", suit: "diamonds" }
const playerHand = [card1, card2, card3]
const sortedBySuit = playerHand.reduce((suits, card) => {
let cardSuit = card.suit
let cardValue = card.value
if (suits[cardSuit] === undefined) suits[cardSuit] = []
suits[cardSuit].push(cardValue)
return suits
}, {})
/*
The value of sortedBySuit after reducing:
{
hearts: [ "9", "K" ],
diamonds: [ "J" ]
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment