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
Convert array of arrays to array of objects grouped together JavaScript
Let's say, we have a two-dimensional array that contains data about some colors and fruits like this:
const data = [
['orange', 'fruit'],
['red', 'color'],
['green', 'color'],
['orange', 'color'],
['banana', 'fruit'],
['blue', 'color'],
['lemon', 'fruit'],
['mango', 'fruit'],
['lemon', 'color'],
];
console.log("Original data:", data);
Original data: [ [ 'orange', 'fruit' ], [ 'red', 'color' ], [ 'green', 'color' ], [ 'orange', 'color' ], [ 'banana', 'fruit' ], [ 'blue', 'color' ], [ 'lemon', 'fruit' ], [ 'mango', 'fruit' ], [ 'lemon', 'color' ] ]
We have to write a function that takes in this array and returns an array in which the different fruits and colors are grouped by their categories.
Like in this example we only have two categories namely 'fruit' and 'color', so we should expect an array of two objects in the output like this:
[
{
group: 'fruit',
value: [ 'orange', 'banana', 'lemon', 'mango' ]
},
{
group: 'color',
value: [ 'red', 'green', 'orange', 'blue', 'lemon' ]
}
]
Note ? In this very example we only have two categories but we are required to write a solution that works for a dynamic number of categories and not just only two.
Using Array.reduce() Method
We will use the Array.prototype.reduce() method and for each subarray we will check if we have an existing group or not. If the group exists, we push the new value into its value property otherwise we create a new object for that group and push it into the array.
const data = [
['orange', 'fruit'],
['red', 'color'],
['green', 'color'],
['orange', 'color'],
['banana', 'fruit'],
['blue', 'color'],
['lemon', 'fruit'],
['mango', 'fruit'],
['lemon', 'color'],
];
const groupData = arr => {
return arr.reduce((acc, val) => {
const [value, groupName] = val;
const groupIndex = acc.findIndex(el => el?.group === groupName);
if(groupIndex !== -1){
acc[groupIndex].value.push(value);
}else{
acc.push({
group: groupName,
value: [value]
});
}
return acc;
}, []);
};
console.log(groupData(data));
[
{ group: 'fruit', value: [ 'orange', 'banana', 'lemon', 'mango' ] },
{
group: 'color',
value: [ 'red', 'green', 'orange', 'blue', 'lemon' ]
}
]
Using Map for Better Performance
For larger datasets, using a Map can be more efficient than findIndex:
const groupDataWithMap = arr => {
const map = new Map();
arr.forEach(([value, groupName]) => {
if (map.has(groupName)) {
map.get(groupName).push(value);
} else {
map.set(groupName, [value]);
}
});
return Array.from(map.entries()).map(([group, value]) => ({
group,
value
}));
};
console.log(groupDataWithMap(data));
[
{ group: 'fruit', value: [ 'orange', 'banana', 'lemon', 'mango' ] },
{ group: 'color', value: [ 'red', 'green', 'orange', 'blue', 'lemon' ] }
]
How It Works
Both methods follow the same logic:
- Iterate through each subarray [value, category]
- Check if the category already exists in our result
- If it exists, add the value to that category's array
- If not, create a new group object with the category and value
Conclusion
The reduce() method provides a clean solution for grouping array data into objects. For better performance with large datasets, consider using Map instead of findIndex().
