Skip to content

Instantly share code, notes, and snippets.

@silencesys
Last active June 18, 2019 09:30
Show Gist options
  • Save silencesys/c0f58084778edb8954d6a29b82391bf4 to your computer and use it in GitHub Desktop.
Save silencesys/c0f58084778edb8954d6a29b82391bf4 to your computer and use it in GitHub Desktop.
Javascript Helper functions

Javascript helpers

Collection of javascript helper functions.

List will be expanded

Array.prototype.groupBy = function(prop) {
return this.reduce(function(groups, item) {
var val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}
var myList = [
{time: '12:00', location: 'mall' },
{time: '9:00', location: 'store' },
{time: '9:00', location: 'mall' },
{time: '12:00', location: 'store' },
{time: '12:00', location: 'market' },
];
var byTime = myList.groupBy('time');
/**
byTime = {
'9:00': [
{time: '9:00', location: 'store' },
{time: '9:00', location: 'mall' },
],
'12:00': [
{time: '12:00', location: 'mall' },
{time: '12:00', location: 'store' },
{time: '12:00', location: 'market'}
]
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment