0

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

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!

2
  • is gdp a fixed value or dynamic? what have you tried? Commented Aug 31, 2022 at 13:38
  • If I understand you correctly, gdp is fixed in that it will be identical for each year. I was trying to use d3.nest but I'm not seeing how to do it. Commented Aug 31, 2022 at 13:40

1 Answer 1

2

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; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.