Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Splitting an array based on its first value - 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]]; console.log(arr);
[ [ 1, 45 ], [ 1, 34 ], [ 1, 49 ], [ 2, 34 ], [ 4, 78 ], [ 2, 67 ], [ 4, 65 ] ]
Each subarray contains exactly two elements. We need to write a function that constructs a new array where all second elements of subarrays with the same first value are grouped together.
For the array above, the expected output should be:
[ [45, 34, 49], // All second values where first value is 1 [34, 67], // All second values where first value is 2 [78, 65] // All second values where first value is 4 ]
Solution Using reduce() and Map
We can use Array.prototype.reduce() with a Map to efficiently group the values:
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 ] ]
How It Works
The algorithm uses an accumulator object containing:
- map: A Map that stores the first value as key and the index in the result array as value
- res: The result array where grouped second values are stored
For each subarray [key, value]:
- If the key doesn't exist in the map, create a new group with the value and store its index
- If the key exists, add the value to the existing group at the stored index
Alternative Approach Using Object
Here's a simpler approach using a plain object:
const arr = [[1, 45], [1, 34], [1, 49], [2, 34], [4, 78], [2, 67], [4, 65]];
const groupByFirstValue = (arr = []) => {
const groups = {};
// Group second values by first value
arr.forEach(([first, second]) => {
if (!groups[first]) {
groups[first] = [];
}
groups[first].push(second);
});
// Return only the grouped arrays
return Object.values(groups);
};
console.log(groupByFirstValue(arr));
[ [ 45, 34, 49 ], [ 34, 67 ], [ 78, 65 ] ]
Conclusion
Both approaches effectively group array elements by their first value. The Map-based solution maintains insertion order and handles edge cases better, while the object-based approach is more straightforward and readable.
