Jerome
Jerome

Reputation: 874

Invert object keys with value array

I am working on a programming challenge. I need to invert this object:

{
   apple: [40, 49],
   orange: [20, 21],
   pear: [2, 50, 19]
}

to come out as

{
   40: "apple",
   49: "apple",
   20: "orange",
   21: "orange",
   2: "pear",
   50: "pear",
   19: "pear",
}

This is pretty easy to do with a for-loop, but one of the rules to the challenge is no for-loops or additional libraries.

Here's my solution using for-loops, is it possible to do it without the use of a for-loop:

var temp = {}
for (var key in fruit) {
    for (var i in fruit[key]) {
        temp[fruit[key][i]] = key;
    }
}
console.log(temp);

Upvotes: 1

Views: 45

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138537

  const temp = Object.fromEntries(Object.entries(fruit).flatMap(([k, vs]) => vs.map(v => [v, k])));

This is basically with loops too, just way more obscure.

Upvotes: 1

mickl
mickl

Reputation: 49985

You can try using array.reduce and Object.entries:

let input = {
   apple: [40, 49],
   orange: [20, 21],
   pear: [2, 50, 19]
};

let result = Object.entries(input).reduce((acc, current) => {
    let [k,v] = current;
    v.forEach(val => acc[val] = k);
    return acc;
}, {})

console.log(result);

Upvotes: 1

Related Questions