0

I made following Array.

I need to group items by categories.

Is it possible to group by category?

I am trying and thinking but too difficult.

Should I just change Array format to make simple?

[
    {
        id: 1,
        name: apple,
        category: {
            name: 'fruit'
        }
    },
    {
        id: 2,
        name: orange,
        category: {
            name: 'frit'
        }
    },
    {
        id: 3,
        name: cucumber,
        category: {
            name: 'vegetable'
        }       
    },
    {
        id: 4,
        name: chicken,
        category: {
            name: 'meat'
        }       
    },
]

Result I want is

[
    {
        category: fruit,
        items: [
            {
                id: 1,
                name: apple,
            },
            {
                id: 2,
                name: orange,
            },
        ]
    },
    {
        category: vegetable,
        items: [
            {
                id: 3,
                name: cucumber,
            },
        ]
    },
    {
        category: meat,
        items: [
            {
                id: 4,
                name: chicken,
            },
        ]
    },
]

thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks

wwwrrrxxx
  • 195
  • 3
  • 16

1 Answers1

0

You need to write a method to go through you array and arrange the items by their category. Something like this:

function groupByCategory (array) {
    let groupedArray = [];
    for (const item of array)
        if (item.category.name) {
            if (!groupedArray[category.name]) groupedArray[category.name] = [];
            groupedArray[category.name].push(item);
    }
    return groupedArray;
}
Tritonal
  • 607
  • 4
  • 16