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.
Therefore, 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.
Example
Following is the code −
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
This will produce the following output in console −
[ [ 45, 34, 49 ], [ 34, 67 ], [ 78, 65 ] ]