Array.prototype doesn't have any grouping functionality, so let's add the groupBy() method. Let's say we have the following array example:
var movies = [
{
"Title": "Inception",
"Year": "2010",
"Director": "Christopher Nolan"
},
{
"Title": "Interstellar",
"Year": "2014",
"Director": "Christopher Nolan"
},
{
"Title": "Avatar",
"Year": "2009",
"Director": "James Cameron"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Director": "Christopher Nolan"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Director": "Christopher Nolan"
}
];
console.table(movies.groupBy('Director'));
The groupBy('Director') method should return 2 groups - 1st "Christopher Nolan" group and 2nd "James Cameron" group. Every group should contain the list of associated movies.
Now let's have a look at the method implementation.