Created
December 16, 2018 11:50
-
-
Save ApoloSiskos/f32cd6d74b246d207a612d5271093584 to your computer and use it in GitHub Desktop.
Group dictionary (array of objects) based on one object (key)
This file contains 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
<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