Convert an array to a 2D array (Square matrix) in javascript

痞子三分冷 提交于 2019-12-08 12:02:19

问题


I have got a little function in javascript and I want to split an array A into a 2d array. I will be used for square matrices. Obviously,I want it to be 2x2 if a square matrix of 2x2 is in the input and so on for 3x3 and. But I'm stuck after having read a first row.So my arr rows are repeated. Does anyone have any ideas about how I can get the next rows read properly.So,for instance,lets say I do have an array

A = [2,1,4,5,1,2,3,1,9]

Then I want my array arr to look like this:

arr = [[2,1,4],[5,1,2],[3,1,9]]

This will later be used for calculation a determinant of a matrix.

function create2Darray(clname) {
  var A = document.getElementsByClassName(clname);
  var arr = new Array();
  var rows = Math.sqrt(A.length);
  for (var i = 0; i < rows; i++) {
    arr[i] = new Array();
    for (var j = 0; j < rows; j++) {
      arr[i][j] = A[j].value;
    }
  }
}

回答1:


You are assigning always the same value. It should be something like:

arr[i][j] = A[i*rows+j].value;

EDIT: Here's a complete function without the DOM manipulation (that is, A is a simple array of integers):

function create2Darray(A) {
  var arr = [];
  var rows = Math.sqrt(A.length);
  for (var i = 0; i < rows; i++) {
    arr[i] = [];
    for (var j = 0; j < rows; j++) {
      arr[i][j] = A[i * rows + j];
    }
  }
  return arr;
}

console.log(create2Darray([1, 2, 3, 4, 5, 6, 7, 8, 9]))


来源:https://stackoverflow.com/questions/16501704/convert-an-array-to-a-2d-array-square-matrix-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!