Two arrays of objects are given:
array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}];
array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}];
The goal is to merge them in a way that each object contains properties from both arrays, excluding the object not present in the first array.
An attempt has been made using the following code snippet:
var mergeArrays = function() {
var array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}];
var array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}];
var newArray = array2.filter(i => array1.map(a=> { if(a.id == i.id) i.qty = a.qty; return i; }));
return newArray.filter(i=> { if(i.qty) return i; });
}
console.log(mergeArrays());
While this method works in some cases, there are inconsistencies depending on the environment. Seeking alternative solutions to address this issue.