JavaScript - Group Objects by Property into Arrays
Last Updated :
13 Jan, 2025
Here are the various approaches to grouping objects by property into arrays
1. Using a for Loop
The for loop is the most basic and widely used approach.
JavaScript
//Driver Code Starts
const a = [
{ cat: 'fruit', name: 'apple' },
{ cat: 'veg', name: 'carrot' },
{ cat: 'fruit', name: 'banana' }
];
const grouped = [];
const groups = {};
//Driver Code Ends
for (let obj of a ) {
if (!groups[obj.cat]) {
groups[obj.cat] = [];
grouped.push(groups[obj.cat]);
}
groups[obj.cat].push(obj);
}
//Driver Code Starts
console.log(grouped);
//Driver Code Ends
Output[
[ { cat: 'fruit', name: 'apple' }, { cat: 'fruit', name: 'banana' } ],
[ { cat: 'veg', name: 'carrot' } ]
]
In this example
- It tracks categories using an object.
- Pushes each object into its respective group.
- Adds groups to the final array.
2. Using reduce()
The reduce() is the functional programming approach to grouping.
JavaScript
//Driver Code Starts
const a = [
{ cat: 'fruit', name: 'apple' },
{ cat: 'veg', name: 'carrot' },
{ cat: 'fruit', name: 'banana' }
];
//Driver Code Ends
const grouped = Object.values(
a.reduce((acc, obj) => {
acc[obj.category] = acc[obj.category] || [];
acc[obj.category].push(obj);
return acc;
}, {})
);
//Driver Code Starts
console.log(grouped);
//Driver Code Ends
Output[
[
{ cat: 'fruit', name: 'apple' },
{ cat: 'veg', name: 'carrot' },
{ cat: 'fruit', name: 'banana' }
]
]
- Uses reduce() to group objects by property.
- Populates the accumulator object with categories.
- Extracts grouped arrays using Object.values().
3. Using Map()
The map() is efficient and ideal for large datasets.
JavaScript
//Driver Code Starts
const a = [
{ cat: 'fruit', name: 'apple' },
{ cat: 'veg', name: 'carrot' },
{ cat: 'fruit', name: 'banana' }
];
//Driver Code Ends
const map = new Map();
a.forEach(obj => {
if (!map.has(obj.cat)) map.set(obj.cat, []);
map.get(obj.cat).push(obj);
});
//Driver Code Starts
const grouped = Array.from(map.values());
console.log(grouped);
//Driver Code Ends
Output[
[ { cat: 'fruit', name: 'apple' }, { cat: 'fruit', name: 'banana' } ],
[ { cat: 'veg', name: 'carrot' } ]
]
4. Using Object.assign()
The Object.assign() method combines with reduce() to group objects.
JavaScript
//Driver Code Starts
const a = [
{ cat: 'fruit', name: 'apple' },
{ cat: 'veg', name: 'carrot' },
{ cat: 'fruit', name: 'banana' }
];
//Driver Code Ends
const grouped = Object.values(
a.reduce((grp, obj) =>
Object.assign(grp, {
[obj.cat]: [...(grp[obj.cat] || []), obj],
}),
{})
);
//Driver Code Starts
console.log(grouped);
//Driver Code Ends
Output[
[ { cat: 'fruit', name: 'apple' }, { cat: 'fruit', name: 'banana' } ],
[ { cat: 'veg', name: 'carrot' } ]
]
- Updates the accumulator with grouped arrays.
- Uses Object.assign() for dynamic property assignment.
5. Using Array.filter()
Array.filter() method groups objects by filtering the array multiple times.
JavaScript
//Driver Code Starts
const a = [
{ cat: 'fruit', name: 'apple' },
{ cat: 'veg', name: 'carrot' },
{ cat: 'fruit', name: 'banana' }
];
//Driver Code Ends
const cats = [...new Set(a.map(obj => obj.cat))];
const grouped = cats.map(cat => a.filter(obj =>
obj.cat === cat));
//Driver Code Starts
console.log(grouped);
//Driver Code Ends
Output[
[ { cat: 'fruit', name: 'apple' }, { cat: 'fruit', name: 'banana' } ],
[ { cat: 'veg', name: 'carrot' } ]
]
- Creates unique categories using Set.
- Filters objects for each category.
6. Using Object.fromEntries()
Combine map() with Object.fromEntries() for a modern approach.
JavaScript
const a = [
{ cat: 'fruit', name: 'apple' },
{ cat: 'veg', name: 'carrot' },
{ cat: 'fruit', name: 'banana' }
];
const grouped = Object.values(
a.reduce((grp, obj) => {
if (!grp[obj.cat]) {
grp[obj.cat] = [];
}
grp[obj.cat].push(obj);
return grp;
}, {})
);
console.log(grouped);
Output[
[ { cat: 'fruit', name: 'apple' }, { cat: 'fruit', name: 'banana' } ],
[ { cat: 'veg', name: 'carrot' } ]
]
- Uses map() and Object.fromEntries() to create an initial structure.
- Populates the structure with objects.
Which Approach Should You Choose?
- for Loop: Best for beginners; simple and easy to understand.
- reduce(): Perfect for functional programmers; clean and expressive.
- Map(): Efficient for handling large datasets.
- Object.assign(): Compact but slightly advanced.
- filter(): Useful for smaller datasets but less efficient.
- Object.fromEntries(): A modern and flexible approach.
Similar Reads
Grouping Nested Array in JavaScript Grouping nested arrays in JavaScript involves arranging arrays within arrays based on a common key or property. There are different approaches to group nested arrays in JavaScript which are as follows: Table of Content Using the reduce() methodUsing the forEach() method with an object as a mapUsing
3 min read
How to Convert Object to Array in JavaScript? In this article, we will learn how to convert an Object to an Array in JavaScript. Given an object, the task is to convert an object to an Array in JavaScript. Objects and Arrays are two fundamental data structures. Sometimes, it's necessary to convert an object to an array for various reasons, such
4 min read
How to Regroup JSON array in JavaScript Regrouping JSON arrays in JavaScript is crucial for organizing data efficiently, simplifying data management tasks, and ensuring better data integration across systems. Here, we will regroup JSON arrays in JavaScript in two methods to achieve this using the reduce method and an iterative approach. T
3 min read
How to Return an Array of Unique Objects in JavaScript ? Returning an array of unique objects consists of creating a new array that contains unique elements from an original array. We have been given an array of objects, our task is to extract or return an array that consists of unique objects using JavaScript approaches. There are various approaches thro
5 min read
JavaScript- Convert an Object to JS Array Objects in JavaScript are the most important data type and form the building blocks for modern JavaScript. These objects are quite different from JavaScriptâs primitive data types (Number, String, Boolean, null, undefined, and symbol). Methods to convert the Objects to JavaScript Array:1. Using Obje
3 min read