Skip to content

Instantly share code, notes, and snippets.

@suyesh
Created August 14, 2017 02:48
Show Gist options
  • Save suyesh/9ec721a80a0e6bfe76ae5f736e503247 to your computer and use it in GitHub Desktop.
Save suyesh/9ec721a80a0e6bfe76ae5f736e503247 to your computer and use it in GitHub Desktop.
/* Popular Ice Cream Totals Quiz
*
* Using the data array and .reduce():
* - return an object where each property is the name of an ice cream flavor and
* each value is an integer that's the total count of that flavor
* - store the returned data in a new iceCreamTotals variable
*
* Note:
* - do not delete the data variable
* - do not alter any of the data content
*/
const data = [
{ name: 'Tyler', favoriteIceCreams: ['Strawberry', 'Vanilla', 'Chocolate', 'Cookies & Cream'] },
{ name: 'Richard', favoriteIceCreams: ['Cookies & Cream', 'Mint Chocolate Chip', 'Chocolate', 'Vanilla'] },
{ name: 'Amanda', favoriteIceCreams: ['Chocolate', 'Rocky Road', 'Pistachio', 'Banana'] },
{ name: 'Andrew', favoriteIceCreams: ['Vanilla', 'Chocolate', 'Mint Chocolate Chip'] },
{ name: 'David', favoriteIceCreams: ['Vanilla', 'French Vanilla', 'Vanilla Bean', 'Strawberry'] },
{ name: 'Karl', favoriteIceCreams: ['Strawberry', 'Chocolate', 'Mint Chocolate Chip'] }
];
let iceCreamTotals = data.map((iceCream) => {
iceCream.favoriteIceCreams.reduce((iceCreamNames, name) => {
if (name in allNames){
iceCreamNames[name]++
} else {
iceCreamNames[name] = 1;
}
return iceCreamNames
}, {})
})
@eduzol
Copy link

eduzol commented Sep 3, 2017

This is a good start but allNames is not defined , nevertheless it helped me to come up with my solution thanks 👍
Please review my solution below
https://gist.github.com/eduzol/1b31c40f926b66904aa818cdec0d0919

@taj
Copy link

taj commented Sep 24, 2017

Here is a solution without using foreach:

let iceCreamTotals = data
    .reduce( (accumulator, currentValue) => {
        return currentValue.favoriteIceCreams.reduce( (accumulator2, iceCream) => {
            accumulator.push(iceCream)
            return accumulator
        }, [] )
    }, [] )
    .reduce( (accumulator, currentValue) => {
         if ( currentValue in accumulator ) {
            accumulator[currentValue]++;
        } else {
            accumulator[currentValue] = 1;
        }
        return accumulator;
    }, {} )

console.log(iceCreamTotals)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment