Created
July 31, 2024 08:15
-
-
Save upalexgill/86bec3c87e579c4f4268e05485ea2a4c to your computer and use it in GitHub Desktop.
Map array of objects with same key using reduce
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 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