Grouping array of array on the basis of elements in JavaScript

When working with arrays of arrays in JavaScript, you might need to group elements based on specific criteria. This article demonstrates how to group the second elements of subarrays that share the same first element.

Problem Statement

Suppose we have an array of arrays where each subarray contains exactly two elements:

const arr = [[1, 45], [1, 34], [1, 49], [2, 34], [4, 78], [2, 67], [4, 65]];
console.log("Input array:", arr);
Input array: [ [ 1, 45 ], [ 1, 34 ], [ 1, 49 ], [ 2, 34 ], [ 4, 78 ], [ 2, 67 ], [ 4, 65 ] ]

We need to group all second elements that have the same first element. The expected output should be:

[
  [45, 34, 49],  // All second elements where first element is 1
  [34, 67],      // All second elements where first element is 2
  [78, 65]       // All second elements where first element is 4
]

Using Array.reduce() with Map

The most efficient approach uses Array.reduce() combined with a Map to track groups and their positions:

const arr = [[1, 45], [1, 34], [1, 49], [2, 34], [4, 78], [2, 67], [4, 65]];

const constructSimilarArray = (arr = []) => {
    const creds = arr.reduce((acc, val) => {
        const { map, res } = acc;
        if (!map.has(val[0])) {
            map.set(val[0], res.push([val[1]]) - 1);
        } else {
            res[map.get(val[0])].push(val[1]);
        }
        return { map, res };
    }, {
        map: new Map(),
        res: []
    });
    return creds.res;
};

console.log(constructSimilarArray(arr));
[ [ 45, 34, 49 ], [ 34, 67 ], [ 78, 65 ] ]

Alternative Approach Using Object

You can also achieve the same result using a plain object instead of a Map:

const arr = [[1, 45], [1, 34], [1, 49], [2, 34], [4, 78], [2, 67], [4, 65]];

const groupByFirstElement = (arr) => {
    const groups = {};
    
    arr.forEach(([first, second]) => {
        if (!groups[first]) {
            groups[first] = [];
        }
        groups[first].push(second);
    });
    
    return Object.values(groups);
};

console.log(groupByFirstElement(arr));
[ [ 45, 34, 49 ], [ 34, 67 ], [ 78, 65 ] ]

How It Works

The Map-based solution works by:

  • Using reduce() to iterate through each subarray
  • Maintaining a Map to track which group index corresponds to each first element
  • If a first element hasn't been seen, creating a new group and storing its index
  • If a first element exists, adding the second element to the existing group

Comparison

Method Performance Readability Memory Usage
Map + reduce() Excellent Moderate Low
Object + forEach() Good High Low

Conclusion

Both approaches effectively group array elements based on their first values. The Map-based solution is more performance-oriented, while the object-based approach offers better readability for simpler use cases.

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

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements