1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| var join = function (arr1, arr2) { let IdObject = {}; for (const obj of arr1) { IdObject[obj.id] = obj; } for (const obj of arr2) { if (IdObject[obj.id]) { Object.assign(IdObject[obj.id], obj); } else { IdObject[obj.id] = obj; } } const sortedObject = Object.values(IdObject).sort((a, b) => { a.id - b.id; }); return sortedObject; };
arr1 = [ { id: 1, x: 1 }, { id: 2, x: 9 }, ]; arr2 = [{ id: 3, x: 5 }];
console.log(join(arr1, arr2)); console.log("end");
|