1

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);

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1
  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.

1 Comment

with loops - but not a for loop - so it's fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.