Skip to content

Instantly share code, notes, and snippets.

@camskene
Created August 30, 2019 16:16
Show Gist options
  • Save camskene/9cdcf2a72fe45af5387809d645602e13 to your computer and use it in GitHub Desktop.
Save camskene/9cdcf2a72fe45af5387809d645602e13 to your computer and use it in GitHub Desktop.
let arr = [
{
title: 'Cat',
tags: ['tag1', 'tag2'],
},
{
title: 'Dog',
tags: ['tag1', 'tag2'],
},
{
title: 'Monkey',
tags: ['tag1'],
},
{
title: 'Squirrel',
tags: ['tag1'],
},
]
let groupedByTag = arr.reduce((acc, node) => {
node.tags.forEach((tag) => {
if (Array.isArray(acc[tag])) {
acc[tag].push(node);
} else {
acc[tag] = [node];
}
});
return acc;
}, {});
console.log(JSON.stringify(groupedByTag, null, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment