How transpose array of mixed data in efficient way in HANA XS / Javascript

48 views Asked by At

I have to transpose data of a HANA table into an array on which to create a json model, so I've got an array like:

[COLOR, TYPE, INFO, DAY, VALUE]

COLOR, TYPE and DAY is the Primary Key and period is the same for all keys:

[BLACK,JEANS,Info01,2020-12-01,25], //start period
[BLACK,JEANS,Info01,2020-12-02,22],
[BLACK,JEANS,Info01,2020-12-03,18],
[BLACK,JEANS,Info01,2020-12-04,33], //end period
[WHITE,SHIRT,Info02,2020-12-01,15], //start period
[WHITE,SHIRT,Info02,2020-12-02,12],
[WHITE,SHIRT,Info02,2020-12-03,58],
[WHITE,SHIRT,Info02,2020-12-04,63], //end period

I would like to transpose it to get the following array:

[BLACK,JEANS,Info01,25,22,18,33],
[WHITE,SHIRT,Info02,15,12,58,63],

Is there an efficient way to do it?

1

There are 1 answers

2
Nina Scholz On

Assuming same dates in order.

You could use a joined key for the first three items and collect the values.

const
    data = [['BLACK', 'JEANS', 'Info01', '2020-12-01', 25], ['BLACK', 'JEANS', 'Info01', '2020-12-02', 22], ['BLACK', 'JEANS', 'Info01', '2020-12-03', 18], ['BLACK', 'JEANS', 'Info01', '2020-12-04', 33], ['WHITE', 'SHIRT', 'Info02', '2020-12-01', 15], ['WHITE', 'SHIRT', 'Info02', '2020-12-02', 12], ['WHITE', 'SHIRT', 'Info02', '2020-12-03', 58], ['WHITE', 'SHIRT', 'Info02', '2020-12-04', 63]],
    result = Object.values(data.reduce((r, a) => {
        const
            keys = a.slice(0, 3),
            key = keys.join('|');
        r[key] = r[key] || keys;
        r[key].push(a[4]);
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }