Lodash - invert method

The video is wrong. How can we build a new object if it is created anew in each iteration? Impossible. We end up with only a single property in the returned object.

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

The values of the input object become the key of the new one, and the keys of the old become the values in the new.

We should be aware that if the input object has duplicated values, only the last to be parsed will be a key in the new object.

1 - _.invert() is defined - Passed!
2 - Returns an object with all keys and values inverted - Passed!
3 - Returns an object with all keys and values inverted - Passed!
1 Like

Ah, I see.

I went beck to check the video and the fourth test wan’t in there so that explains why she passed

1 Like

I didn’t look at the test but I wonder if it doesn’t just invert an object, then invert that object to see if the original is restored?

Eg.

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

const {invert} = _
const obj = {1: 'one', 2: 'two', 3: 'three'}
const objinv = invert(obj)
const invobj = invert(objinv)
console.log(objinv)
console.log(invobj)
{ one: '1', two: '2', three: '3' }
{ '1': 'one', '2': 'two', '3': 'three'
1 Like

Playing around with the Object methods…

  inverter (obj) {
    const keys = Object.values(obj)
    const values = Object.keys(obj)
    const map = keys.map((key, i) => [key, values[i]])
    return Object.fromEntries(map)
  }

Ignore this if you haven’t yet reached the unit on iterators.

Note: This will not work in the LE since it is not supported by the Node version it employs. Will work with version 12 and above.


Chrome dev console

const _ = {
  invert (object) {
    const invertedObject = {};
    for (let key in object) {
      const originalValue = object[key];
      invertedObject[originalValue] = key
    }
    return invertedObject;
  },
  inverter (obj) {
    const keys = Object.values(obj)
    const values = Object.keys(obj)
    entries = keys.map((key, i) => [key, values[i]])
    return Object.fromEntries(entries)
  }
}
undefined
const {inverter} = _
undefined
obj = {1: 'one', 2: 'two', 3: 'three'}
{1: 'one', 2: 'two', 3: 'three'}
objinv = inverter(obj)
{one: '1', two: '2', three: '3'}
invobj = inverter(objinv)
{1: 'one', 2: 'two', 3: 'three'}
1 Like