Grouping nested array in JavaScript

Suppose, we have an array of values like this −

const arr = [
    {
        value1:[1,2],
        value2:[{type:'A'}, {type:'B'}]
    },
    {
        value1:[3,5],
        value2:[{type:'B'}, {type:'B'}]
    }
];

We are required to write a JavaScript function that takes in one such array. Our function should then prepare an array where the data is grouped according to the "type" property of the objects.

Therefore, for the above array, the output should look like −

const output = [
    {type:'A', value: [1,2]},
    {type:'B', value: [3,5]}
];

Example

The code for this will be −

const arr = [
    {
        value1:[1,2],
        value2:[{type:'A'}, {type:'B'}]
    },
    {
        value1:[3,5],
        value2:[{type:'B'}, {type:'B'}]
    }
];

const groupValues = (arr = []) => {
    const res = [];
    arr.forEach((el, ind) => {
        const thisObj = this;
        el.value2.forEach(element => {
            if (!thisObj[element.type]) {
                thisObj[element.type] = {
                    type: element.type,
                    value: []
                }
                res.push(thisObj[element.type]);
            };
            if (!thisObj[ind + '|' + element.type]) {
                thisObj[element.type].value =
                thisObj[element.type].value.concat(el.value1);
                thisObj[ind + '|' + element.type] = true;
            };
        });
    }, {})
    return res;
};

console.log(groupValues(arr));

Output

And the output in the console will be −

[
    { type: 'A', value: [ 1, 2 ] },
    { type: 'B', value: [ 1, 2, 3, 5 ] }
]

How It Works

The function uses a clever approach with the thisObj context to track which types have been encountered and prevent duplicate value concatenation. The key mechanism involves:

  • Creating unique objects for each type in the result array
  • Using a tracking key pattern ind + '|' + element.type to avoid adding the same values multiple times
  • Concatenating value1 arrays only when a type appears for the first time in each object

Conclusion

This approach efficiently groups nested array data by type while avoiding duplicate values. The tracking mechanism ensures each value set is added only once per group, creating clean grouped output.

Updated on: 2026-03-15T23:19:00+05:30

855 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements