Skip to content
Advertisement

Mapping arrays into object with values as an array

I would like to create an object containing all the values from the array first and the values from second as an array of values, assuming that this key references multiple numbers such that given the arrays:

first = [3,0,5,3]
second = [1,3,10,5]

my output would be {0: 3, 3: [1,5], 5: 10}

This is what I have tried:

const newObj = {}
for(let i = 0; i < first.length; i++){
    newObj[first[i]] =  second[i] ? [ second[i] ] : second[i]
}

This is what I get:

{ '0': [ 3 ], '3': [ 5 ], '5': [ 10 ] }

Advertisement

Answer

This is the easiest method to understand as it’s just the bare logic written in its entirety.

for (let i = 0; i < first.length; i++) {
    if (first[i] in newObj) { // If key exists already
        if (typeof newObj[first[i]] === "number") { // and if it's a number
            newObj[first[i]] = [newObj[first[i]]]; // then we wrap it into an array
        }

        newObj[first[i]].push(second[i]); // add the new number
    } else {
        newObj[first[i]] = second[i]; // if it doesn't exist then add it
    }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement