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
}, {})
})
@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