[Django]-Transform JavaScript 2D Array

2๐Ÿ‘

โœ…

You could take an object for the column position of the values and collect the data by date and column.

var data = [["VHR", "2019-02-1", 23], ["VNA", "2019-02-1", 34], ["PAP", "2019-02-1", 50], ["VHR", "2019-02-2", 92], ["VNA", "2019-02-2", 13], ["PAP", "2019-02-2", 65], ["VHR", "2019-02-3", 192], ["VNA", "2019-02-3", 43], ["PAP", "2019-02-3", 11]],
    cols = { VHR: 1, VNA: 2, PAP: 3 },
    result = data.reduce((r, [key, date, value]) => {
        var row = r.find(([d]) => d === date);
        if (!row) {
            r.push(row = [date, 0, 0, 0]);
        }
        row[cols[key]] = value;
        return r;    
    }, [["date", "VHR", "VNA", "PAP"]]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
๐Ÿ‘คNina Scholz

2๐Ÿ‘

you can group them by date, then using Object.entries loop through the grouped result and transform it to [date, "VHR", "VNA", "PAP"]

const data = [
  ["VHR", "2019-02-1", 23],
  ["VNA", "2019-02-1", 34],
  ["PAP", "2019-02-1", 50],
  ["VHR", "2019-02-2", 92],
  ["VNA", "2019-02-2", 13],
  ["PAP", "2019-02-2", 65],
  ["VHR", "2019-02-3", 192],
  ["VNA", "2019-02-3", 43],
  ["PAP", "2019-02-3", 11]
];

const grouped = data.reduce((all, [key, date, value]) => {

  all[date] = {
    ...all[date],
    [key]: value
  };

  return all;
}, {});

const result = ["date", "VHR", "VNA", "PAP"].concat(
  Object.entries(grouped).map(([date, obj]) => [date, ...Object.values(obj)])
);

console.log(result);
๐Ÿ‘คTaki

Leave a comment