2722. Join Two Arrays by ID

2722. 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.

// 陣列裡的物件如果出現一樣的 id ,要 merge ; 不一樣的話,直接包含在 result array
// merge 規則 : key 值沒有重複就直接 merge,有重複的 key,arr2 的要覆蓋掉 arr1 的
var join = function (arr1, arr2) {
  const ans = {};

  for (let i = 0; i < arr1.length; i++) {
    ans[arr1[i].id] = arr1[i];
  }

  for (let i = 0; i < arr2.length; i++) {
    if (arr2[i].id in ans) {
      ans[arr2[i].id] = { ...ans[arr2[i].id], ...arr2[i] };
    } else {
      ans[arr2[i].id] = arr2[i];
    }
  }
  const arr = Object.values(ans);
  return arr;
};

const arr1 = [
  { id: 1, x: 9 },
  { id: 2, x: 1 },
];
const arr2 = [{ id: 3, x: 5 }];

join(arr1, arr2);