Search code examples
javascriptarraysarrayobject

How to Group array of objects with same keys using javascripts?


I want to make an array of objects grouped by the date property.

let data = [
        { Age: "(60-100)", Date: "28/05/20" },
        { Age: "(60-100)", Date: "28/05/20" },
        { Age: "(4-6)", Date: "28/05/20" },
        { Age: "(60-100)", Date: "29/05/20" },
        { Age: "(38-43)", Date: "29/05/20" },
        { Age: "(4-6)", Date: "29/05/20" },
        { Age: "(38-43)", Date: "30/05/20" },
        { Age: "(38-43)", Date: "30/05/20" }
    ];

I want the output like

 result = [
        { Date: "28/05/20", "(60-100)": 2, "(4-6)": 1 },
        { Date: "29/05/20", "(38-43)": 1, "(4-6)": 1, "(60-100)": 1 },
        { Date: "30/05/20", "(38-43)": 2 },
    ]

Solution

  • Try this:

    function groupByDate(data){
        let groupedData = [];
        data.forEach(element => {
            //Search for the object containing the specified date
            let objIndex = groupedData.findIndex(object => {return object.Date == element.Date;})
            //If date is not created, create it
            if (objIndex == -1){
                groupedData.unshift({Date: element.Date})
                objIndex = 0;
            }
            //If age is not created, create it. Else add 1 to specified age.
            if(typeof groupedData[objIndex][element.Age] == 'undefined'){
                groupedData[objIndex][element.Age] = 1;
            } else {
                groupedData[objIndex][element.Age]++;
            }
        });
        return groupedData;
    }
    

    If you also want to sort by date, you could check out this post. Hope it helped you!