Skip to main content
Back to problems
#2794
Easy JavaScript

Create object from two arrays

64.3% acceptance
Mar 31, 2026
11
3
Given two arrays keysArr and valuesArr, return a new object obj. Each key-value pair in obj should come from keysArr[i] and valuesArr[i]. If a duplicate key exists at a previous index, that key-value should be excluded. In other words, only the first key should be added to the object. If the key is not a string, it should be converted into a string by calling String() on it.

Solution

TypeScript
Time O(n)
Space O(1)
LeetCode
solution.ts
type JSONValue =
  | null
  | boolean
  | number
  | string
  | JSONValue[]
  | { [key: string]: JSONValue };

function createObject(
  keysArr: JSONValue[],
  valuesArr: JSONValue[],
): Record<string, JSONValue> {
  const obj: Record<string, JSONValue> = {};
  for (let i = 0; i < keysArr.length; i++) {
  const key = String(keysArr[i]);
  if (!(key in obj)) {
    obj[key] = valuesArr[i];
  }
  }
  return obj;
}