How to make a matrix from two arrays column and rows in JS?

Issue

I have a json data format:
[{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];
from that I have generate two arrays one for header column cols and other for row rows

let notes = [{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];

let cols = ['n1', 'n2', 'n3'];
let rows = ['subject1', 'subject2'];

let matrix = Array(cols.length).fill(Array(rows.length).fill(0));
for(const x of notes){
    let {note, subject, value} = x;
    matrix[cols.indexOf(note)][rows.indexOf(subject)] = note;
}
console.log(matrix)

Expected result:

[[10,0,0],[0,0,19]]

But My goal is to render it as an HTML table looks like this:

Subj\Note Note1 Note2 Note3
Subj1 10 0 0
subj2 0 0 19

How could I do that, Any suggestion or help is much appreciated!

Solution

You’re on the right track. Just a few points:

  • Your intention is to declare and create a 2D array but that’s not actually the case
  • You have rows and columns mixed up
  • Instead of = note you should have = value.
let notes = [{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];

let cols = ['n1', 'n2', 'n3'];
let rows = ['subject1', 'subject2'];

let matrix = Array(rows.length).fill().map(() => Array(cols.length).fill(0));
for(const x of notes) {
    let {note, subject, value} = x;
    matrix[rows.indexOf(subject)][cols.indexOf(note)] = value;
}
console.log(matrix)

Answered By – PeterKA

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.