Skip to content

Instantly share code, notes, and snippets.

@learosema
Last active January 30, 2019 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save learosema/6e8a60ca7ba3274658f4 to your computer and use it in GitHub Desktop.
Save learosema/6e8a60ca7ba3274658f4 to your computer and use it in GitHub Desktop.
Group table-like arrays by column

Groups a table-like array by a column

##Example##

[{name: 'Gene', team: 'team alpha'},
 {name: 'George', team: 'team beta'},
 {name: 'Steve', team: 'team gamma'},
 {name: 'Paula', team: 'team beta'},
 {name: 'Scruath of the 5th sector', team: 'team gamma'}].group('team');

// Result: 
{
    "team alpha":
        [{"name":"Gene","team":"team alpha"}],
    "team beta":
        [{"name":"George","team":"team beta"},
         {"name":"Paula","team":"team beta"}],
    "team gamma":
        [{"name":"Steve","team":"team gamma"},
         {"name":"Scruath of the 5th sector","team":"team gamma"}]
}

##License

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2019 Lea Rosema

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

          DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.
Array.prototype.group = function(column,i,r) {
for(r={},i=0;i<this.length;i++)
if (this[i][column]){
if(!r[this[i][column]])r[this[i][column]]=[]
r[this[i][column]].push(this[i])
}
return r
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment