0

Would like to create a two dimensional m x n array in javascript, based on the number of columns, that is inputed as an argument in my function, the rows would be created from another argument which would be an array.

What I look to achieve - Desired Result:

var arr = [0,1,2,3,4,5,6,7,8,9]

function TwoDimensionalArray(numRows, numCols) {
//Magic happens here!
}

TwoDimensionalArray(arr, 4);

As you can see the is a 3 x 4 matrix below and a desired result

[[0,1,2,3], [4,5,6,7],[8,9]]

The input size doesn't make the difference, the number of columns is the key factor and the determinant factor.

What I have currently - Not Desired Result:

var arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13]

function TwoDimensionalArray(numRows, numColumns) {
   var twoD = [];

   for (var row = 0; row < numRows.length; ++row) {

     var cardIndex = numRows[row]

      // console.log(numRows[row]);

       var columns = [];

     for(var j =0; j < numColumns; ++j) {
        columns[j] = cardIndex;
    }

    twoD[cardIndex] = columns;
}

return twoD;
 };


var matrixTwoD = TwoDimensionalArray(arr, 4);

console.log(matrixTwoD);
console.log(matrixTwoD[0][0]);
console.log(matrixTwoD[0][1]);
console.log(matrixTwoD[0][2]);
console.log(matrixTwoD[0][3]);

My current code creates an array that repeats each of the elements 4 times each until the number 13 with a column size of 4: [[0,0,0,0], [1,1,1,1]....[13,13,13,13]]

Maybe am doing something wrong in my for loop or not approaching the problem correctly. But anything to point me in the right direction to get the above desire result.

Bouns

Also would anyone also be kinda to point me to additional resources for matrix algebra pertaining to this sort of problem and anything in general that would help for self study.

Thanks a bunch!

1
  • A nice library: mathjs.org/index.html It offers matrices manipulation. Commented Dec 29, 2015 at 5:44

2 Answers 2

2

Keep it simple, slice the input Array into sections of numCols length

function TwoDimensionalArray(arr, numCols) {
    var arr2d = [],
        i;
    if (numCols) // safety first!
        for (i = 0; i < arr.length; i += numCols)
            arr2d.push(arr.slice(i, i + numCols));

    return arr2d;
}

  • if (numCols) prevents an infinite loop in the case numCols was not provided or is 0
  • for (i = 0; i < arr.length; i += numCols) counts up from 0 in numCols, e.g. i = 0, 4, 8, 16, ... until we reach a number greater than arr.length
  • arr.slice(i, i + numCols) creates a sub-Array of Array starting from (including) index i and ending at (excluding) index i + numCols, i.e. we get a numCols long Array starting with the item at index i of arr
  • arr2d.push appends a new item to the end of arr2d

Putting all these together, we can see that we are building a new Array arr2d from sections of the Array arr

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

2 Comments

Thank you! But could you elaborate more on the process in terms of why this solution? Just for learning purposes. appreciate it :)
@Amechi I've added more detail in bullet points rather than comments, as I wasn't sure exactly which parts you wanted to know about
0

calculate columns required and then use slice method of array.

start index = (numColumns * i) end index = numColumns * (i + 1)

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

function TwoDimensionalArray(numRows, numColumns) {
  var columns = [];

  for (var i = 0; i !== Math.ceil(numRows.length / numColumns); i++) {
    columns[i] = numRows.slice((numColumns * i), numColumns * (i + 1))
      //console.log((numColumns * i) + " " +numColumns * (i + 1))
  }
  return columns;
};

var matrixTwoD = TwoDimensionalArray(arr, 4);

console.log(matrixTwoD);
console.log(matrixTwoD[0][0]);
console.log(matrixTwoD[0][1]);
console.log(matrixTwoD[0][2]);
console.log(matrixTwoD[0][3]);

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.