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

Time:06-02

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!

CodePudding user response:

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)

CodePudding user response:

I can think of couple ways to do it. One way would be to loop thru cols and rows using forEach and find the matching value in notes or return 0 to construct the matrix as follows:

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 = []

rows.forEach(row => {
  let newRow = []
  cols.forEach(col => {
    newRow.push(notes.find(n => n.note === col && n.subject === row)?.value || 0)
  })
  matrix.push(newRow)
})

console.log(matrix)

Another method might be to use reduce to loop thru cols and rows to get your matrix:

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 = rows.reduce((accRow, row) => {
  accRow.push(cols.reduce((accCol, col) => {
    accCol.push(notes.find(n => n.note === col && n.subject === row)?.value || 0)
    return accCol
  }, []))
  return accRow
}, [])

console.log(matrix)

  • Related