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:
  1. var movies = [
  2. {
  3. "Title": "Inception",
  4. "Year": "2010",
  5. "Director": "Christopher Nolan"
  6. },
  7. {
  8. "Title": "Interstellar",
  9. "Year": "2014",
  10. "Director": "Christopher Nolan"
  11. },
  12. {
  13. "Title": "Avatar",
  14. "Year": "2009",
  15. "Director": "James Cameron"
  16. },
  17. {
  18. "Title": "The Dark Knight",
  19. "Year": "2008",
  20. "Director": "Christopher Nolan"
  21. },
  22. {
  23. "Title": "Batman Begins",
  24. "Year": "2005",
  25. "Director": "Christopher Nolan"
  26. }
  27. ];
  28. console.table(movies.groupBy('Director'));
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.
  1. Array.prototype.groupBy = function(field){
  2. let groupedArr = [];
  3. this.forEach(function(e){
  4. //look for an existent group
  5. let group = groupedArr.find(g => g['field'] === e[field]);
  6. if (group == undefined){
  7. //add new group if it doesn't exist
  8. group = {field: e[field], groupList: []};
  9. groupedArr.push(group);
  10. }
  11. //add the element to the group
  12. group.groupList.push(e);
  13. });
  14. return groupedArr;
  15. }
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