Overview
Implement dataMerge(arr1, arr2, key) that merges objects from both arrays matching on key. Properties from arr2 override arr1.
Examples
dataMerge(
[{ id: 1, name: 'Alice' }],
[{ id: 1, age: 25 }],
'id'
); // [{ id: 1, name: 'Alice', age: 25 }]Solution
Reveal solution
function dataMerge(arr1, arr2, key) {
const map = new Map();
for (const item of arr1) map.set(item[key], { ...item });
for (const item of arr2) {
const existing = map.get(item[key]) || {};
map.set(item[key], { ...existing, ...item });
}
return Array.from(map.values());
}data-merging.js
Data Merging
mediumcodingJavaScriptObjects
Overview
Implement dataMerge(arr1, arr2, key) that merges objects from both arrays matching on key. Properties from arr2 override arr1.
Examples
dataMerge(
[{ id: 1, name: 'Alice' }],
[{ id: 1, age: 25 }],
'id'
); // [{ id: 1, name: 'Alice', age: 25 }]Solution
Reveal solution
function dataMerge(arr1, arr2, key) {
const map = new Map();
for (const item of arr1) map.set(item[key], { ...item });
for (const item of arr2) {
const existing = map.get(item[key]) || {};
map.set(item[key], { ...existing, ...item });
}
return Array.from(map.values());
}NameTopicDifficulty
103 of 103 problems