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

62% accept rate
feedback

4 Answers

up vote 7 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
feedback

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? – Peretz Oct 12 '11 at 22:03
feedback
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
feedback

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
feedback

Your Answer

 
or
required, but never shown
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.