Last active
February 7, 2019 08:08
-
-
Save tolotrasmile/b040da9302949e494dbd7e465d0df61d to your computer and use it in GitHub Desktop.
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
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