Skip to content

2822. Inversion of Object 👍

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
type JSONValue =
  | null
  | boolean
  | number
  | string
  | JSONValue[]
  | { [key: string]: JSONValue };
type Obj = Record<string, JSONValue> | Array<JSONValue>;

function invertObject(obj: Obj): Record<string, JSONValue> {
  const ans: Record<string, JSONValue> = {};

  for (const [key, value] of Object.entries(obj)) {
    const valueKey = value as string;
    if (ans.hasOwnProperty(valueKey)) {
      const curr = ans[valueKey];
      if (!Array.isArray(curr)) {
        ans[valueKey] = [curr];
      }
      (ans[valueKey] as JSONValue[]).push(key);
    } else {
      ans[valueKey] = key;
    }
  }

  return ans;
}