Last active
July 9, 2019 21:48
-
-
Save Juandresyn/84079e1506eab6d5eafc2fb18ede47cc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// As a prototype | |
/* | |
* @param property string - The object propperty to group by. | |
*/ | |
Array.prototype.groupBy = function (property) { | |
const filtered = this.reduce(function(item, x) { | |
if (!item[x[property]]) { item[x[property]] = []; } | |
item[x[property]].push(x); | |
return item; | |
}, []); | |
const temp = {}; | |
Object.keys(filtered).forEach(i => temp[i] = filtered[i]); | |
return temp; | |
} | |
// As a function | |
/* | |
* @param arr array - The array to group. | |
* @param property string - The object propperty to group by. | |
*/ | |
export const groupBy = function (arr, property) { | |
const filtered = arr.reduce(function(item, x) { | |
if (!item[x[property]]) { item[x[property]] = []; } | |
item[x[property]].push(x); | |
return item; | |
}, []); | |
const temp = {}; | |
Object.keys(filtered).forEach(i => temp[i] = filtered[i]); | |
return temp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment