As an example
I have two arrays
const tempData = [
{ day: "Mon", temp: 33.6 },
{ day: "Tue", temp: 34.6 },
{ day: "Wed", temp: 33.1 },
{ day: "Fri", temp: 35.6 }
];
const coughData = [
{ day: "Mon", count: 2 },
{ day: "Wed", count: 1 },
{ day: "Thur", count: 1 },
{ day: "Fri", count: 3 },
{ day: "Sat", count: 1 }
];
I need to merge these arrays into one so that if the day matches the count value adds to that object if it doesn't match it adds both objects to the array.
Don't know if the explanation isn't so clear but
The expected result should be like this:
const data = [
{ day: "Mon", temp: 33.6, count: 2 },
{ day: "Tue", temp: 34.6 },
{ day: "Wed", temp: 33.1, count: 1 },
{ day: "Thur", count: 1 },
{ day: "Fri", temp: 35.6, count: 3 },
{ day: "Sat", count: 1 }
];
I am trying to use map function like so but can't understand how do I return both the objects if they don't match:
const data = tempData.map(temp => {
coughData.map(cough => {
if (temp.day === cough.day) {
return (temp.count = cough.count);
} else {
return cough;
}
});
return temp;
});
Array.mapwill transform array rows, it's name is map, So you have to useArray.reduce.