awariat
awariat

Reputation: 382

JS arrays merge and sum

I have arrays

{"BS-WHITE":3,"BS-BOX":1}//input value
{"BS-WHITE":2,"BS-BOX":0,"BS-WHITE-1":1}//output value

And I would like to merge them to get arrays in array something like this:

[["BS-WHITE",3,2],["BS-BOX",1,0],["BS-WHITE-1",0,1]]

If value doesn't exist should be 0.

Upvotes: 1

Views: 80

Answers (1)

Nithin Thampi
Nithin Thampi

Reputation: 3679

It's not clear if you want an output object or array.

Anyways..You can try something like below.

If you need an output array.

a = {"BS-WHITE":3,"BS-BOX":1}//input value
b = {"BS-WHITE":2,"BS-BOX":0,"BS-WHITE-1":1}

c = [...new Set([...Object.keys(a), ...Object.keys(b)])];

result = c.map((key) => {
   return  {
        [key]: [(a[key] || 0), (b[key] || 0)] 
    }   
});

console.log(result);

If you need an output object.

a = {"BS-WHITE":3,"BS-BOX":1}//input value
b = {"BS-WHITE":2,"BS-BOX":0,"BS-WHITE-1":1}

c = [...new Set([...Object.keys(a), ...Object.keys(b)])];

result = c.reduce((acc,key) => {
        acc[key] = [(a[key] || 0), (b[key] || 0)] 
        return acc;
  
}, {});

console.log(result);

If you need array of arrays

a = {"BS-WHITE":3,"BS-BOX":1}//input value
b = {"BS-WHITE":2,"BS-BOX":0,"BS-WHITE-1":1}

c = [...new Set([...Object.keys(a), ...Object.keys(b)])];

result = c.map(key => {
        return [key , (a[key] || 0), (b[key] || 0)]
  
});

console.log(result);

Upvotes: 2

Related Questions