Skip to content
Advertisement

Implementing Lodash Invert

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement