#2822
Easy JavaScript Inversion of object
61.5% acceptance
Mar 31, 2026
17
1
Given an object or an array obj, return an inverted object or array invertedObj.
The invertedObj should have the keys of obj as values and the values of obj as keys. The indices of array should be treated as keys.
The function should handle duplicates, meaning that if there are multiple keys in obj with the same value, the invertedObj should map the value to an array containing all corresponding keys.
It is guaranteed that the values in obj are only strings.
Solution
TypeScript
Time O(n)
Space O(1)
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 result: Record<string, JSONValue> = {};
for (const key in obj) {
const val = String((obj as any)[key]);
if (val in result) {
if (Array.isArray(result[val])) {
(result[val] as JSONValue[]).push(key);
} else {
result[val] = [result[val] as string, key];
}
} else {
result[val] = key;
}
}
return result;
}