I have a method that merges keys and indexes from an array into an object.
I'm stuck with ways to compress this method, and I don't know what I can do to make it simpler.
Goal
- get an array of objects with keys
- return an object with a unique key and the matching indexes
Code (simplified)
const items = [
{
"key": 0
},
{
"key": 2
},
{
"key": 4
},
{
"key": 4
}
]
function mergeItems (items) {
const helperObj = {}
// loop over items
items.forEach((item, itemIdx) => {
const { key } = item
// got key in helper obj? push index
if (key in helperObj) {
helperObj[key].push(itemIdx)
} else {
// create new array and set index
helperObj[key] = [itemIdx]
}
});
return helperObj
}
console.log(mergeItems(items));
Expected output:
{
"0": [0],
"2": [1],
"4": [2,3]
}
Question
Is there a way to do this without creating a helper object?
result
. \$\endgroup\$