iT邦幫忙

2023 iThome 鐵人賽

DAY 25
0
Software Development

LELECOCODE 每一天系列 第 25

Day 25: Leetcode 小挑戰,30 Days of JavaScript

  • 分享至 

  • xImage
  •  

Day 25: Join Two Arrays by ID

Given two arrays arr1 and arr2, return a new array joinedArray. All the objects in each of the two inputs arrays will contain an id field that has an integer value. joinedArray is an array formed by merging arr1 and arr2 based on their id key. The length of joinedArray should be the length of unique values of id. The returned array should be sorted in ascending order based on the id key.

If a given id exists in one array but not the other, the single object with that id should be included in the result array without modification.

If two objects share an id, their properties should be merged into a single object:

If a key only exists in one object, that single key-value pair should be included in the object.
If a key is included in both objects, the value in the object from arr2 should override the value from arr1.

var join = function(arr1, arr2) {
    
};

Example 1:
Input:
arr1 = [
{"id": 1, "x": 1},
{"id": 2, "x": 9}
],
arr2 = [
{"id": 3, "x": 5}
]
Output:
[
{"id": 1, "x": 1},
{"id": 2, "x": 9},
{"id": 3, "x": 5}
]

Example 2:
Input:
arr1 = [
{"id": 1, "x": 2, "y": 3},
{"id": 2, "x": 3, "y": 6}
],
arr2 = [
{"id": 2, "x": 10, "y": 20},
{"id": 3, "x": 0, "y": 0}
]
Output:
[
{"id": 1, "x": 2, "y": 3},
{"id": 2, "x": 10, "y": 20},
{"id": 3, "x": 0, "y": 0}
]

Example 3:
Input:
arr1 = [
{"id": 1, "b": {"b": 94},"v": [4, 3], "y": 48}
]
arr2 = [
{"id": 1, "b": {"c": 84}, "v": [1, 3]}
]
Output: [
{"id": 1, "b": {"c": 84}, "v": [1, 3], "y": 48}
]


暴力解

var join = function(arr1, arr2) {
    const combined = arr1.concat(arr2);
    const merged = {};

    combined.forEach((obj) => {
        const id = obj.id;
        if (merged[id]) {
            merged[id] = {...merged[id], ...obj};
        } else {
            merged[id] = {...obj};
        };
    });

    const joinArray = Object.values(merged);
    return joinArray;
};

網友解

var join = function(arr1, arr2) {
     const newObj  = {};
    const arrs = [...arr1, ...arr2]
    for(let index =0; index<=arrs.length-1; index++){
        newObj[arrs[index].id] ={ ...newObj[arrs[index].id],
         ...arrs[index]};
    };
    return Object.values(newObj)
};

網友解 2

var join = function(arr1, arr2) {
    const result = {};
    for (let i = 0; i < arr1.length; i++) {
        result[arr1[i].id] = arr1[i];
    } 
    for (let i = 0; i < arr2.length; i++) {
        if (result[arr2[i].id]) {
            for (const key in arr2[i]) result[arr2[i].id][key] = arr2[i][key];  
        } else {
            result[arr2[i].id] = arr2[i];
        }
    } 

    return Object.values(result);
};

上一篇
Day 24: Leetcode 小挑戰,30 Days of JavaScript
下一篇
Day 26: Leetcode 小挑戰,30 Days of JavaScript
系列文
LELECOCODE 每一天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言