如何从 JS 中的两个数组列和行创建一个矩阵?

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

我有一个json数据格式:
[{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];
由此我生成了两个数组,一个用于 header 列 cols,另一个用于行 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)

预期结果:

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

但我的目标是将其呈现为 HTML table 如下所示:

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

我该怎么做,非常感谢任何建议或帮助!

我可以想到几种方法来做到这一点。一种方法是使用 forEach 遍历 colsrows 并在 notes 或 return 0 中找到匹配值来构建矩阵如下:

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)

另一种方法可能是使用 reduce 循环遍历 colsrows 以获得矩阵:

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)

你走在正确的轨道上。简单几点:

  • 您的意图是声明并创建一个二维数组,但实际上并非如此
  • 您混淆了 rowscolumns
  • 而不是 = note 你应该 = 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)