Skip to content

Instantly share code, notes, and snippets.

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 ApoloSiskos/f32cd6d74b246d207a612d5271093584 to your computer and use it in GitHub Desktop.
Save ApoloSiskos/f32cd6d74b246d207a612d5271093584 to your computer and use it in GitHub Desktop.
Group dictionary (array of objects) based on one object (key)
<div style="background:green;" id="one"></div>
<script>
Array.prototype.groupBy = function(prop) {
return this.reduce(function(groups, item) {
const val = item[prop]
groups[val] = groups[val] || []
groups[val].push(item)
return groups
}, {})
}
const events = [
{ 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' },
]
const groupedByTime = events.groupBy('time')
document.getElementById("one").innerHTML = JSON.stringify(groupedByTime, null, 2);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment