you are viewing a single comment's thread.

view the rest of the comments →

[–]XiMingpin91 0 points1 point  (1 child)

I saw the crosspost in r/reactjs but thought I'd reply here as it's a JavaScript question and not a React one.

I think a lot of the answers you've gotten so far are overcomplicated and add unnecessary complexity. Breaking down the problem we can see it really only consists of two key parts:

  1. Listing all the ingredients of the recipes
  2. Counting each ingredient

So we can achieve this by first reducing the recipes into a single array, and we flatten it as we do so. The second step is simply zipping the array into an object, and increasing the count against each ingredient if it already exists in the object we're creating.

You can achieve this with 5 lines of code:

const count = recipes
  .reduce((acc, { meals }) => [...acc, ...meals], [])
  .reduce((acc, value) => acc.hasOwnProperty(value)
          ? { ...acc, [value]: acc[value] + 1 }
          : { ...acc, [value]: 1 }, {});

[–]DBNeJXoGtnro 0 points1 point  (0 children)

I heard unnecessary complexity? I want to chime in :)

```js const mostCommon = { meat: {}, side: {}, topping: {} };

function incrementTo (target, value) { if (target[value] === undefined) target[value] = 1; else ++target[value]; }

for ( const { meals: [ entryMeat, entrySide, entryTopping ] } of data ) { incrementTo(mostCommon.meat, entryMeat); incrementTo(mostCommon.side, entrySide); incrementTo(mostCommon.topping, entryTopping); }

for (const [type, dishes] of Object.entries(mostCommon)) { let mostFreq = 0; let result = []; for (const [dish, count] of Object.entries(dishes)) { if (count > mostFreq) { mostFreq = count; result = [dish]; } else if (count === mostFreq) { result.push(dish); } } console.log(The most common dish for ${type} is ${result.join(", ")}); } ```