Lodash Implement _.invert

I am working through the Lodash exercises and I am confused at the output I receive when testing it out in node.

I understand how the code should work in theory, however when I went to test it the results were not what I expected.

The code which is validated as working via node is:

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

So, to test this I created the following object outside of the _ object:

let newObject = {
  prop1: 'testing',
  prop2: 'this',
  prop3: 'out'

Then I logged the result to the console.


When I ran the file in node

node _.js

This is what was returned

{ originalValue: 'prop3' }

I am confused how this code passes the test, yet when I run it in node it seems to fail. Any help is appreciated.

tested, perhaps. and not much.
valid? not so much

Hello, @cthunda303.

Welcome to the forums.

When we make an assignment to a variable, we overwrite any previous assignment. Consider what this line does:

Rather than assigning a new object to invertedObject with each iteration of your for loop, how would you go about adding key: value pairs to your existing invertedObject?

The exercise’s built in test for the _.invert function only tests one object with one property, so it isn’t a thorough test. Your test was much better, and you found your function did not return the desired value. Now you have the opportunity to make corrections.

1 Like

Thanks @midlindner! I revised my code, and was able to solve it!

1 Like