1

I need to do an union on an array like the UNION sql statement.

my original array :

const prices = [
{name:'product_name1', price_a:1.0, price_b:null, price_c:null},
{name:'product_name1', price_a:null, price_b:2.0, price_c:3.0},
{name:'product_name2', price_a:2.0, price_b:null, price_c:null},
{name:'product_name2', price_a:null, price_b:null, price_c:1.0},
]

my wanted array :

const prices = [
{name:'product_name1', price_a:1.0, price_b:2.0, price_c:3.0},
{name:'product_name2', price_a:2.0, price_b:null, price_c:1.0},
]

Any idea how to do this ?

U Rogel
  • 1,893
  • 15
  • 30
sorcer1
  • 117
  • 3
  • 11

2 Answers2

0

You could reduce the array and look for same name object and update the prices properties.

const
    prices = [{ name: 'product_name1', price_a: 1.0, price_b: null, price_c: null }, { name: 'product_name1', price_a: null, price_b: 2.0, price_c: 3.0 }, { name: 'product_name2', price_a: 2.0, price_b: null, price_c: null }, { name: 'product_name2', price_a: null, price_b: null, price_c: 1.0 }],
    result = prices.reduce((r, { name, ...prices }) => {
        var temp = r.find(o => o.name === name);
        if (temp) {
            Object.entries(prices).forEach(([k, v]) => v === null || (temp[k] = v));
        } else {
            r.push(temp = { name, ...prices });
        }
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You would basically need to merge elements with the same key based on some logic.
the simplest case is if you need to overwrite the values. Then you would use a spread operator.

Yet if you need to apply different logic, say summation, then you'll have to write it using array's map and reduce methods.
Check answers to this question for many different ways to do that
Cheers!

Ivan Satsiuk
  • 333
  • 2
  • 9