Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Imagine I have an array A=Array(1,2,3,4,5,6,7,8,9) and I want it to convert into 2-dimensional array (matrix of NxM), for instance like this: A=Array(Array(1,2,3),Array(4,5,6),Array(7,8,9)).

Note, that rows and columns of the matrix is changable.

Thank you.

share|improve this question
add comment

4 Answers

up vote 9 down vote accepted

Something like this?

function listToMatrix(list, elementsPerSubArray) {
    var matrix = [], i, k;

    for (i = 0, k = -1; i < list.length; i++) {
        if (i % elementsPerSubArray === 0) {
            k++;
            matrix[k] = [];
        }

        matrix[k].push(list[i]);
    }

    return matrix;
}

Usage:

var matrix = listToMatrix([1, 2, 3, 4, 4, 5, 6, 7, 8, 9], 3);
// result: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
share|improve this answer
1  
Exactly what I needed. Thanx man. –  Bakhtiyor Dec 20 '10 at 18:05
1  
@Bakhtiyor: Glad if it helped ;) –  elusive Dec 20 '10 at 18:09
add comment
function matrixify( source, count )
{
    var matrixified = [];
    var tmp;
    // iterate through the source array
    for( var i = 0; i < source.length; i++ )
    {
        // use modulous to make sure you have the correct length.
        if( i % count == 0 )
        {
            // if tmp exists, push it to the return array
            if( tmp && tmp.length ) matrixified.push(tmp);
            // reset the temporary array
            tmp = [];
        }
        // add the current source value to the temp array.
        tmp.push(source[i])
    }
    // return the result
    return matrixified;
}

If you want to actually replace an array's internal values, I believe you can call the following:

source.splice(0, source.length, matrixify(source,3));
share|improve this answer
add comment

How about something like:

var matrixify = function(arr, rows, cols) {
    var matrix = [];
    if (rows * cols === arr.length) {
        for(var i = 0; i < arr.length; i+= cols) {
            matrix.push(arr.slice(i, cols + i));
        }
    }

    return matrix;
};

var a = [0, 1, 2, 3, 4, 5, 6, 7];
matrixify(a, 2, 4);

http://jsfiddle.net/andrewwhitaker/ERAUs/

share|improve this answer
add comment

Simply use two for loops:

var rowNum = 3;
var colNum = 3;
var k = 0;
var dest = new Array(rowNum);

for (i=0; i<rowNum; ++i) {
  var tmp = new Array(colNum);
  for (j=0; j<colNum; ++j) {
    tmp[j] = src[k];
    k++;
  }
  dest[i] = tmp;
}
share|improve this answer
 
Could you re-write it in C# please? –  Clark Kent Oct 12 '11 at 22:03
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.