-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray-merge.0.1.js
More file actions
36 lines (33 loc) · 825 Bytes
/
array-merge.0.1.js
File metadata and controls
36 lines (33 loc) · 825 Bytes
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
35
36
/*
Merge two Arrays of Objects, remove the object that has as same "id" as the other one
and sort according to the "id"
*/
const array1 = [
{ id: 1, name: "John" },
{ id: 2, name: "Alice" },
{ id: 4, name: "Daniel" },
{ id: 6, name: "Shiffman" },
];
const array2 = [
{ id: 2, age: 30 },
{ id: 6, name: "Bob" },
{ id: 5, name: "Pikaso" },
{ id: 3, name: "Julian" },
];
function mergArrObj(arObj1, arObj2) {
const merged = [...arObj1]; // copy
for (let i = 0; i < arObj2.length; i++) {
let matched = false;
for (let j = 0; j < merged.length; j++) {
if (merged[j].id === arObj2[i].id) {
matched = true;
break;
}
}
if (!matched) {
merged.push(arObj2[i]);
}
}
return merged.sort((a, b) => a.id - b.id);
}
console.log(mergArrObj(array1, array2));