Re-creating the Lodash Library : .invert()

Hello all,
I was having trouble with the .invert method in the exercise above (https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/pjs-javascript-capstone/projects/lodash). I used the get help video (https://youtu.be/av5JiKektzE?t=1290) to complete it , but I do not understand how it works. Below is the method:

invert (object) {

let invertedObj = {};

for (let key in object) {

  const originalValue = object[key];

  invertedObject = {originalValue: key}

}; return invertedObject;

},

How is returning invertedObject inverting the whole object? As far as I can tell, it is just reassigning that variable over and over? It is identical to the function in the video as far as I can tell, so I don’t think its incorrect I just feel like I am missing something important?

1 Like

First, let’s look at what an inverted object looks like…

{1: 'a', 2: 'b', 3: 'c'}  =>  {a: '1', b: '2', c: '3'}

Note how the key and value are swapped for each property.

So we would first create an empty object, then iterate over our given object’s keys, in turn, then create an item for the new object where the value becomes the key, and the key becomes the value.

This is not conducive to building the new object since it is replacing it on each iteration and will end up with only one property.

invertedObj = {}
for (let key in object) {
    invertedObj[object[key]] = key
}
return invertedObj
2 Likes

Yes. This video has been the subject of discussion before. As you pointed out, your code/the video solution code overwrites the object with each iteration.

1 Like

Sorry to bring up yesterdays news. I wasn’t able to find the previous thread when I searched for it. I’ll be more thorough in the future.

No worries. That wasn’t meant as any kind of dig at you for not researching. Just as notice that the video in question provides an incorrect solution. Kudos to you for noticing that the video solution is wrong. :slightly_smiling_face:

Also, the aforementioned previous discussion may only have been in a mod-only area of the forums.

1 Like

Thanks for the solution!
I found that problem as well, and it was nice to confirm that my own solution was right.

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

Thanks

1 Like

Yours is more verbose and literal. Nothing at all wrong with that. I tend to work things into simpler expressions wherever I can. Not to dissuade anyone. You are on the right path, is the main thing.

1 Like