Skip to content

Instantly share code, notes, and snippets.

@eduzol
Forked from suyesh/popcorn.js
Last active July 10, 2018 03:37
Show Gist options
  • Save eduzol/1b31c40f926b66904aa818cdec0d0919 to your computer and use it in GitHub Desktop.
Save eduzol/1b31c40f926b66904aa818cdec0d0919 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
*
* Notes:
* - 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.reduce((acc, values ) => {
values.favoriteIceCreams.forEach((name)=>{
if (name in acc){
acc[name]++;
} else {
acc[name] = 1;
}
});
return acc;
} , {});
console.log(iceCreamTotals);
@nissan
Copy link

nissan commented Jul 10, 2018

Thank you for posting this, it helped me grasp the reduce() function better.
My actual code for this problem is below

let iceCreamTotals = data.reduce((accumulator, item) =>{
    item.favoriteIceCreams.map(iceCream => accumulator[iceCream] = accumulator[iceCream]? accumulator[iceCream] + 1:1);
    return accumulator;
},{});
console.log(iceCreamTotals);

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