Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to group array with objects by the property

Does anyone know of a way to group an array of objects by two property.
I have array like this:

    [
    {
        index: 4,
        name: "car",
        price: [10,20,30]
    },
    {
        index: 4,
        name: "car",
        price: [40,50,60]
    },
    {
        index: 3,
        name: "bike",
        price: [40,50,60]
    },
    {
        index: 2,
        name: "scooter",
        price: [10,20,60]
    },
    {
        index: 2,
        name: "scooter",
        price: [70]
    },
]

so I would like that the output looks like this

[
    {
        index: 4,
        name: car,
        price: [40,50,60,10,20,30]
    },
    {
        index: 3,
        name: bike,
        price: [40,50,60]
    },
    {
        index: 2,
        name: scooter,
        price: [10,20,60, 70]
    }
]

Objects that have the same name and index, connect, i.e. connect the price array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could take an emoty object for grouing along with an array for the grouping keys and build a string with values, like

4|car

of

{ index: 4, name: "car", price: [10, 20, 30] }

for a key which reflects index and name.

Then push all prices to the according group. At the end take only the values as result.

const
    data = [{ index: 4, name: "car", price: [10, 20, 30] }, { index: 4, name: "car", price: [40, 50, 60] }, { index: 3, name: "bike", price: [40, 50, 60] }, { index: 2, name: "scooter", price: [10, 20, 60] }, { index: 2, name: "scooter", price: [70] }],
    keys = ['index', 'name'],
    grouped = Object.values(data.reduce(
        (r, { price, ...o }) => {
            const key = keys.map(k => o[k]).join('|');
            (r[key] ??= { ...o, price: [] }).price.push(...price);
            return r;
        },
        Object.create(null)
    ));

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading