Create Object from Two Arrays Problem
#2794
Description
LeetCode Problem 2794.
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.
Example 1:
Input: keysArr = ["a", "b", "c"], valuesArr = [1, 2, 3]
Output: {"a": 1, "b": 2, "c": 3}
Explanation: The keys "a", "b", and "c" are paired with the values 1, 2, and 3 respectively.
Example 2:
Input: keysArr = ["1", 1, false], valuesArr = [4, 5, 6]
Output: {"1": 4, "false": 6}
Explanation: First, all the elements in keysArr are converted into strings. We can see there are two occurrences of "1". The value associated with the first occurrence of "1" is used: 4.
Example 3:
Input: keysArr = [], valuesArr = []
Output: {}
Explanation: There are no keys so an empty object is returned.
Constraints:
keysArrandvaluesArrare valid JSON arrays2 <= JSON.stringify(keysArr).length, JSON.stringify(valuesArr).length <= 5 * 10^5keysArr.length === valuesArr.length
Solution
Approach: Walk the indices and keep the first key
We want String(key) -> value pairs, where the first occurrence of a key wins.
Object.fromEntriesis the wrong tool: a later duplicate would overwrite the earlier value.- Loop over the indices, convert the key with
String(), and skip it if the object already owns that key. - Add the pair with
Object.definePropertyinstead ofobj[key] = value. Plain assignment to the key"__proto__"would change the prototype rather than create a property. - Check for duplicates with
hasOwnProperty, notin, so inherited names like"toString"do not count as duplicates.
Complexity: Time O(n), space O(n).
/**
* @param {Array} keysArr
* @param {Array} valuesArr
* @return {Object}
*/
var createObject = function (keysArr, valuesArr) {
const obj = {};
for (let i = 0; i < keysArr.length; i++) {
const key = String(keysArr[i]);
if (Object.prototype.hasOwnProperty.call(obj, key)) continue; // first one wins
Object.defineProperty(obj, key, {
value: valuesArr[i],
writable: true,
enumerable: true,
configurable: true,
});
}
return obj;
};