0

I'm working on a challenge that requires me to implement the .invert() method myself. Below is my solution but the expected outcome doesn't match with the actual outcome returned. Please see the second block below.

Implemented .invert() method:

const _ = {
  invert(object) {
    let newObject = {};
    for (let key in object) {
      const originalValue = object[key]
      newObject = {
        originalValue: key
      }
    }
    return newObject;
  }
};

Tested with below code:

var obj1 = { 'a': '1', 'c': '1', 'b': '2' };
console.log(_.invert(obj1));

And I expected to see below is returned:

{ '1': 'c', '2': 'b' }

Actually returned value was as below:

{ originalValue : 'c'}

I'm doing something terribly wrong, but can't figure out what... Can someone help?

2
  • newObject = {originalValue: key} should be newObject = {[originalValue]: key}. See documentation for computed properties: tylermcginnis.com/computed-property-names Commented Apr 24, 2020 at 16:55
  • @HunterMcMillen perfect! It got me one step closer but it only returns {'1':'c'} not the remaining {'2':'b'}. Any idea what's missing?
    – B_12
    Commented Apr 24, 2020 at 17:01

3 Answers 3

3

Instead of assigning a new value for newObject every loop, try just adding a new key to the current object:

const _ = {
  invert (object) {
    let newObject = {};

    for (let key in object) {
      const originalValue = object[key];
      newObject[originalValue] = key;
    }
    
    return newObject;
  }
};

EDIT: as this has been accepted as the answer, I would like to mention that, personally, I like better the solution presented by Ori Drori.

That said, this answer is closer to the original implementation by the question author and I thought it was a better way to understand the necessary change. But if you, coming to this answer just for the code, I'd invite you to try understand and using Ori Drori's version.

1

Solve this using reduce.

var obj = { 'a': '1', 'c': '1', 'b': '2' };
const res = Object.entries(obj).reduce((a, [k, v]) => ({...a, [v]: k}), {});

console.log(res);

1

Convert to an array of pairs of [key, value] using Object.entries(), then map and and flip the pairs to [value, key]. Convert back to an object using Object.fromEntries():

const obj = { 'a': '1', 'c': '1', 'b': '2' };

const result = Object.fromEntries(
  Object.entries(obj)
    .map(([k, v]) => [v, k])
)

console.log(result);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.