Reputation: 163
I'm struggling to find an elegant and reliable way of merging two arrays in vanilla JS or d3.js, where
For example, two arrays of the form
A =
[
{
year : 2001,
gdp : 1.1,
population : 1100
},
{
year : 2002,
gdp : 1.2,
population : 1200
},
]
B =
[
{
year : 2000,
gdp : 1.0,
rainfall : 100
},
{
year : 2001,
gdp : 1.1,
rainfall : 110
}
]
would ideally combine to give
C =
[
{
year : 2000,
gdp : 1.0,
population : null,
rainfall : 10
},
{
year : 2001,
gdp : 1.1,
population : 1100,
rainfall : 110
},
{
year : 2002,
gdp : 1.2,
population : 1200,
rainfall : null
},
]
I can usually figure this kind of thing out but this one has got me really stuck!
Upvotes: 0
Views: 81
Reputation: 386550
You could build an array of all items, get the keys and build an empty object as pattern for an empty object. Then group by year
and get the values. Apply sorting if necessary.
const
a = [{ year: 2001, gdp: 1.1, population: 1100 }, { year: 2002, gdp: 1.2, population: 1200 }],
b = [{ year: 2000, gdp: 1.0, rainfall: 100 }, { year: 2001, gdp: 1.1, rainfall: 110 }],
items = [...a, ...b],
empty = Object.fromEntries(Object.keys(Object.assign({}, ...items)).map(k => [k, null])),
result = Object
.values(items.reduce((r, o) => {
r[o.year] ??= { ...empty };
Object.assign(r[o.year], o);
return r;
}, {}))
.sort((a, b) => a.year - b.year);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2