The Object.groupBy in JavaScript is used to organize an array of objects into groups based on a specified property.
It essentially takes an array and categorizes its elements, making it easier to handle or process grouped data.
Here are examples to understand it:
Example-1
const movies = [
{ title: "Inception", genre: "Sci-Fi" },
{ title: "The Dark Knight", genre: "Action" },
{ title: "Interstellar", genre: "Sci-Fi" },
{ title: "Pulp Fiction", genre: "Crime" }
];
// Grouping movies by genre
const groupByGenre = Object.groupBy(movies, (movie) => {
return movie.genre;
});
/*
Output:
{
"Sci-Fi": [
{ title: "Inception", genre: "Sci-Fi" },
{ title: "Interstellar", genre: "Sci-Fi" }
],
"Action": [
{ title: "The Dark Knight", genre: "Action" }
],
"Crime": [
{ title: "Pulp Fiction", genre: "Crime" }
]
}
*/
console.log(groupByGenre);
Example-2
const movies = [
{ title: "Inception", rating: 8.8 },
{ title: "The Dark Knight", rating: 9.0 },
{ title: "Interstellar", rating: 8.6 },
{ title: "Pulp Fiction", rating: 8.9 },
];
// Grouping movies by rating range
const groupByRating = Object.groupBy(movies, (movie) => {
if (movie.rating >= 9.0) {
return "Highly Rated";
} else {
return "Regular";
}
});
/*
Output:
{
"Regular": [
{ title: "Inception", rating: 8.8 },
{ title: "Interstellar", rating: 8.6 },
{ title: "Pulp Fiction", rating: 8.9 }
],
"Highly Rated": [
{ title: "The Dark Knight", rating: 9.0 }
]
}
*/
console.log(groupByRating);
If you need the implementation of Object.groupBy, here is a simple version you could use:
Object.groupBy = function (list, keyGetter) {
const map = {};
list.forEach((item) => {
const key = keyGetter(item);
if (!map[key]) {
map[key] = [];
}
map[key].push(item);
});
return map;
};