Skip to content

Instantly share code, notes, and snippets.

@tolotrasmile
Last active February 7, 2019 08:08
Show Gist options
  • Save tolotrasmile/b040da9302949e494dbd7e465d0df61d to your computer and use it in GitHub Desktop.
Save tolotrasmile/b040da9302949e494dbd7e465d0df61d to your computer and use it in GitHub Desktop.
const array = [
{ id: 1, category: 'Apple' },
{ id: 1, category: 'Orange' },
{ id: 3, category: 'Orange' },
{ id: 4, category: 'Grape' },
{ id: 5, category: 'Grape' },
]
function groupBy(array, key) {
const keys = (array, key) => array.reduce((acc, item) => acc.add(item[key]), new Set());
return Array
.from(keys(array, key))
.map(k => array.filter(x => x[key] === k))
}
console.log(groupBy(array, 'id'))
function group(array, key) {
const withKeys = array.reduce((acc, item) => {
acc[key] = acc[key] || [];
acc[key].push(item);
return acc;
}, {})
return Object.values(withKeys);
}
console.log(group(array, 'id'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment