Skip to content

Instantly share code, notes, and snippets.

@upalexgill
Created July 31, 2024 08:15
Show Gist options
  • Save upalexgill/86bec3c87e579c4f4268e05485ea2a4c to your computer and use it in GitHub Desktop.
Save upalexgill/86bec3c87e579c4f4268e05485ea2a4c to your computer and use it in GitHub Desktop.
Map array of objects with same key using reduce
const items = [
{
key: 'categoryA',
sequence: 1
},
{
key: 'categoryB',
sequence: 2
},
{
key: 'categoryA',
sequence: 3
},
{
key: 'categoryB',
sequence: 4
},
];
const result = items.reduce((prev, curr) => {
if (!prev.hasOwnProperty(curr.key)) {
prev[curr.key] = [];
}
prev[curr.key].push(curr);
return prev;
}, {});
console.log(result);
/*
{
"categoryA": [
{
"key": "categoryA",
"sequence": 1
},
{
"key": "categoryA",
"sequence": 3
}
],
"categoryB": [
{
"key": "categoryB",
"sequence": 2
},
{
"key": "categoryB",
"sequence": 4
}
]
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment