Search code examples
javascriptarraysobjectfilter

Javascript - Filter and/or Group Array of Objects by property


Hi I have this array of objects

{
    "events": [
        {
            "id": 0,
            "description": "Monthly play with friends",
            "categoryId": 0
        },
        {
            "id": 1,
            "description": "Buy Goods",
            "categoryId": 2
        },
        {
            "id": 2,
            "description": "Yoga",
            "categoryId": 1
        },
        {
            "id": 3,
            "description": "Lunch",
            "categoryId": 0
        },
        {
            "id": 4,
            "description": "Feed wild & free Bearded Dragons",
            "categoryId": 3
        },
        {
            "id": 5,
            "description": "Come to help our little friends",
            "categoryId": 3
        },
        {
            "id": 6,
            "description": "Come and share your expertise",
            "categoryId": 3
        },
        {
            "id": 7,
            "description": "Dinner with Brother",
            "categoryId": 2
        }
    ]
}

I need to show the items grouped by CategoryId, showing CategoryID as the title of the group, and then list the items of that category inside.

CategoryId 0 Monthly play with friends Lunch

CategoryId 1 Yoga

CategoryId 2 Buy Goods Dinner with Brother

and so on....


Solution

  • one ez for loop should suffice :

    const data = { events: ... }
    
    var obj = {};
    for (let event of data.events) {
      // if empty, creates a array
      obj[event.categoryId] = obj[event.categoryId] || [];
      // add data in that array
      obj[event.categoryId].push(event);
    }
    

    now you have a table for each categoryId, feel free to display it as you like

    for (let categoryId in obj) {
      console.log(categoryId, obj[categoryId]);
    // or
    //  console.log(categoryId, obj[categoryId].map(x => x.description).join(','));
    }