invertLoading saved progress…

invert

invert flips an object: every value becomes a key and every key becomes its value. It's how you turn a lookup table around — a name → id map into id → name. Its companion invertBy handles the case invert can't: when several keys share a value, it groups them into arrays instead of letting one overwrite the others.

Implement both. invert(obj) returns a new object with keys and values swapped (values coerced to string keys, later wins on collision). invertBy(obj, iteratee) maps each computed group key to an array of the original keys that produced it.

Signature

function invert(obj) {}            // { a: 1, b: 2 } -> { 1: 'a', 2: 'b' }
function invertBy(obj, iteratee) {} // group original keys by iteratee(value)

Examples

invert({ a: 1, b: 2 });       // { '1': 'a', '2': 'b' }
invert({ a: 1, b: 1 });       // { '1': 'b' }  — collision, later wins
invertBy({ a: 1, b: 2, c: 1 });                 // { '1': ['a', 'c'], '2': ['b'] }
invertBy({ a: 1, b: 2 }, (v) => v % 2 ? 'odd' : 'even'); // { odd: ['a'], even: ['b'] }

Notes

  • Values become keys — and object keys are strings, so a numeric value 1 becomes the key '1'.
  • invert collisions — if two keys share a value, the later one wins; the earlier is lost.
  • invertBy groups — instead of overwriting, it collects all original keys for a value into an array.
  • invertBy default iteratee — the identity of the value, so invertBy(obj) groups by the raw value.
  • New object, no mutation — return a fresh object; the input is untouched.
Loading editor…