Created
August 30, 2019 16:16
-
-
Save camskene/9cdcf2a72fe45af5387809d645602e13 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
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