Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge disjoint object arrays in JS

I’m struggling to find an elegant and reliable way of merging two arrays in vanilla JS or d3.js, where

  • the "rows" of the series do not necessarily match;
  • objects may share some but not all attributes;
  • "missing" attributes are filled in as null.

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading