# Grouping array of array on the basis of elements in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of arrays of numbers like this −

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

Each subarray is bound to contain strictly two elements. We are required to write a function that constructs a new array where all second elements of the subarrays that have similar first value are grouped together.

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

const output = [
[45, 34, 49],
[34, 67],
[78, 65]
];

We can make use of the Array.prototype.reduce() method that takes help of a Map() to construct the required array.

Therefore, let’s write the code for this function −

## Example

The code for this will be −

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));

## Output

The output in the console will be −

[ [ 45, 34, 49 ], [ 34, 67 ], [ 78, 65 ] ]
Published on 20-Oct-2020 12:14:26