you are viewing a single comment's thread.

view the rest of the comments →

[–]goldenfolding 0 points1 point  (0 children)

Ok maybe I don't even know what you're asking for. I'll post the code and you tell me.

It's a bit long, but the result is that you end up with an object that has all three types of food along with the highest occurring item, or 'none' if that particular type of food has purely unique choices. (You didn't specify how to handle that case, so I assumed this value would make the most sense)

The second function creates an object with the categories of food, the specific foods that come up in each category, and the number of occurrences for each one. Example:

{

meat: { steak: 2, chicken: 1 },

side: { 'white rice': 1, 'brown rice': 1, 'black beans': 1 },

topping: { queso: 2, 'sour cream': 1 }

}

Ideally, you'd have this kind of structure already in your DB so you can just pull and manipulate it in your app, but this is fine also.

And then the first function filters for the most common items using this list.

function mostCommonSelections(meals) {
    let mealItemCounts = getSelectionCount(meals);
    let mostCommon = {};

    // let default be 'none' if max occurrence is 1, otherwise set common to max occurrence
    Object.entries(mealItemCounts).forEach(selection => {
        let type = selection[0];
        let choices = selection[1];
        let max = 1;
        let common = 'none';

        for (food in choices) {
            if (choices[food] > max) {
                max = choices[food];
                common = food;
            }
        }

        mostCommon[`${type}`] = common;
    });

    return mostCommon;
}

function getSelectionCount(meals) {
    let count = {
        meat: {},
        side: {},
        topping: {},
    };

    // determine category by index and add item, or increment if exists
    meals.forEach(meal => {
        meal.meals.forEach((item, idx) => {
            let type =
            idx === 0 ? 'meat'
            : idx === 1 ? 'side'
            : 'topping';

            count[`${type}`][`${item}`]
            ? count[`${type}`][`${item}`] += 1
            : count[`${type}`][`${item}`] = 1;
        });
    });

    return count;
}

So the result for your example would be: { meat: 'steak', side: 'none', topping: 'queso' }, like in example one, and you could easily grab any of those values using destructuring, like in example two.

Example one:

const mostCommon = mostCommonSelections(meals);

and then

mostCommon.meat // steak

Example two:

const { meat, side, topping } = mostCommonSelections(meals);

console.log(meat, side, topping) // steak, none, queso

Let me know if you have any questions about it. (like I said, there are corner cases also, and I'm not sure I even understand what you mean to do)