Having encountered a perplexing issue that I can't seem to comprehend... here is what I am attempting to achieve.
Presented with the following array of objects,
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 },
];
My initial approach involved using nested loops to add keys based on ingredient names and incrementing the count as I iterate through, like so:
let ingredientCount = {};
for (i = 0; i < products.length; i += 1) {
for (j = 0; j < products[i].ingredients.length; j += 1) { //loop ingredients
ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
}
}
The resulting ingredientCount object should resemble: { "artichoke": 1 "mushrooms": 2 } ***
The challenge at hand is to achieve the same outcome using map and reduce functions instead of loops.
let ingredientCount = {}
ingredientCount =
products.filter((value) => {
// filter out arrays within ingredients
// resulting in
/*
[ingredients: ['artichoke', 'sundried tomatoes', 'mushrooms']
,ingredients: ['roma', 'sundried tomatoes', 'goats cheese', 'rosemary']
,ingredients: ['black beans', 'jalapenos', 'mushrooms']
,ingredients: ['blue cheese', 'garlic', 'walnuts']
,ingredients: ['spinach', 'kalamata olives', 'sesame seeds']
*/
}).map((value) => {
/* extract ingredients and map this array to
arthichoke: ['artichoke','artichoke','artichoke']
sundried tomatoes: ['sundried tomatoes']
etc...
*/
}).reduce((acc, value) => {
/* reduce arrays within each key to numbers.
resulting in
artichokes: artichokes.length (i.e. 3 )
sundried toamatoes: 1
*/
})
Is there a way to achieve the same result using the array methods mentioned above without the need for loops?
Thank you in advance.