How to convert simple array into two-dimensional array (matrix) with Javascript

后端 未结 15 1832
独厮守ぢ
独厮守ぢ 2020-11-27 04:26

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 N x M), for ins

15条回答
  •  清歌不尽
    2020-11-27 05:14

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

提交回复
热议问题