Skip to content

Instantly share code, notes, and snippets.

@AndrewBuntsev
Created May 25, 2020 02:19
Show Gist options
  • Save AndrewBuntsev/c5fbbb755f362ed5ade46c0f90080c1a to your computer and use it in GitHub Desktop.
Save AndrewBuntsev/c5fbbb755f362ed5ade46c0f90080c1a to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment