Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Grouping array of array on the basis of elements in JavaScript
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 ] ]
Advertisements