'How merge two arrays conditional on inner keys?
I have two arrays which look like below:
array1 = [
{
id: 'A',
values: [
{ date: '1/1/2022', measure: 231 },
{ date: '1/2/2022', measure: 31 },
],
},
{
id: 'B',
values: [
{ date: '1/1/2020', measure: 51 },
{ date: '1/2/2020', measure: 66 },
],
},
];
const array2 = [
{
id: 'AA',
values: [
{ date: '1/1/2022', measure: 23 },
{ date: '1/2/2022', measure: 67 },
],
},
{
id: 'BB',
values: [
{ date: '1/1/2020', measure: 90 },
{ date: '1/2/2020', measure: 100 },
],
},
];
The arrays have unequal ids but it is known key A should be merged with AA, B should be merged with BB and so on. Dates are equal in case of A and AA, B and BB, etc.
I want to merge A and AA (and rest) as below:
arrayFinall = [
{
id: 'A-AA',
values: [
{date:"1/1/2022", measure1: 231, measure2: 23 },
{date: "1/2/2022", measure1: 31, measure2: 67}},
],
{
id: 'B-BB',
values: [
{date:"1/1/2020", measure1: 51, measure1: 90},
{date:"1/2/2020", measure1: 66, measure1: 100},
}
]
Either creating a new array that has both measures and the date for a new key A-AA or push measure from array2 into appropriate position in array 1 work in this case.
Solution 1:[1]
const array1 = [
{
id: 'A',
values: [
{ date: '1/1/2022', measure: 231 },
{ date: '1/2/2022', measure: 31 },
],
},
{
id: 'B',
values: [
{ date: '1/1/2020', measure: 51 },
{ date: '1/2/2020', measure: 66 },
],
},
];
const array2 = [
{
id: 'AA',
values: [
{ date: '1/1/2022', measure: 23 },
{ date: '1/2/2022', measure: 67 },
],
},
{
id: 'BB',
values: [
{ date: '1/1/2020', measure: 90 },
{ date: '1/2/2020', measure: 100 },
],
},
];
function mergeArrays(array1, array2) {
const result = [];
const keys = Object.keys(array1);
keys.forEach((key) => {
const array1Values = array1[key].values;
const array2Values = array2[key].values;
const values = [];
array1Values.forEach((value) => {
const date = value.date;
const measure1 = value.measure;
const measure2 = array2Values.find((value2) => value2.date === date).measure;
values.push({ date, measure1, measure2 });
});
result.push({ id: `${array1[key].id}-${array2[key].id}`, values });
});
return result;
}
console.log(JSON.stringify(mergeArrays(array1, array2), null, 2));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Parvesh Kumar |
