返回介绍

solution / 2700-2799 / 2794.Create Object from Two Arrays / README_EN

发布于 2024-06-17 01:02:59 字数 3072 浏览 0 评论 0 收藏 0

2794. Create Object from Two Arrays

中文文档

Description

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:

  • keysArr and valuesArr are valid JSON arrays
  • 2 <= JSON.stringify(keysArr).length, JSON.stringify(valuesArr).length <= 5 * 105
  • keysArr.length === valuesArr.length

Solutions

Solution 1

function createObject(keysArr: any[], valuesArr: any[]): Record<string, any> {
  const ans: Record<string, any> = {};
  for (let i = 0; i < keysArr.length; ++i) {
    const k = String(keysArr[i]);
    if (ans[k] === undefined) {
      ans[k] = valuesArr[i];
    }
  }
  return ans;
}
/**
 * @param {Array} keysArr
 * @param {Array} valuesArr
 * @return {Object}
 */
var createObject = function (keysArr, valuesArr) {
  const ans = {};
  for (let i = 0; i < keysArr.length; ++i) {
    const k = keysArr[i] + '';
    if (ans[k] === undefined) {
      ans[k] = valuesArr[i];
    }
  }
  return ans;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文