1

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 Answer 1

4

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]))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.