I'm working through an exercise using the underscore library to perform a count of item occurrences.
Specifically, I have this array:
products = [
{ name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
{ name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
{ name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
{ name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
{ name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
];
And am trying to use map(), flatten() and reduce() to determine the number of times each ingredient shows up.
When I use the code below, ingredientCount returns undefined values:
var ingredientCount = { "{ingredient name}": 0 };
_(products).chain()
.map(function(obj) {return obj.ingredients;})
.flatten().reduce(function(memo, x) {
return memo[x] = (memo[x] || 0) + 1;
}, ingredientCount)
.value();
However, if I remove the second argument to reduce() and include the initial object in the function body, everything works as expected, i.e.:
var ingredientCount = { "{ingredient name}": 0 };
_(products).chain()
.map(function(obj) {return obj.ingredients;})
.flatten().reduce(function(memo, x) {
return ingredientCount[x] = (ingredientCount[x] || 0) + 1;
})
.value();
Can somebody help explain why this is the case?
Thanks!