es-toolkit/docs/reference/object/invert.md
원동휘 1918eec3d9
feat(invert): add invert (#125)
* feat: Add invert

* feat: Add test for invert

* feat: Add bench for invert

* docs: Add docs for invert

* docs: fix .vitepress for invert

* chore: Change incorrectly specified path

* chore: Refactor benchmark tests

* feat: refactor type invert

* Update src/object/invert.ts

---------

Co-authored-by: Sojin Park <raon0211@gmail.com>
2024-07-05 10:08:39 +09:00

769 B

invert

Creates a new object by swapping the keys and values of the given object.

This function takes an object and creates a new object where the keys are the values and the values are the keys of the original object. If there are duplicate values in the input object, the key that appears last will be used as the new key.

Signature

function invert<K extends string | number | symbol, V extends string | number | symbol>(
  obj: Record<K, V>
): { [key in V]: K };

Parameters

  • obj (Record<K, V>): The object to invert.

Returns

({ [key in V]: K }): A new object with keys and values inverted.

Examples

const obj = { a: 1, b: 1, c: 2 };
const result = invert(obj);
// result will be { 1: 'b', 2: 'c' }