Tuesday, January 15, 2019

JavaScript Array groupBy method

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.
  
Array.prototype.groupBy = function(field){
  let groupedArr = [];
  this.forEach(function(e){
    //look for an existent group
    let group = groupedArr.find(g => g['field'] === e[field]);
    if (group == undefined){
      //add new group if it doesn't exist
      group = {field: e[field], groupList: []};
      groupedArr.push(group);
    }
    
    //add the element to the group
    group.groupList.push(e);
  });
  
  return groupedArr;
}


You can try it on JSFiddler:
http://jsfiddle.net/AndrewBuntsev/7syen826/
Don't forget to press F12 to display browser's console

No comments:

Post a Comment