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

后端 未结 15 1685
独厮守ぢ
独厮守ぢ 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));
    
    0 讨论(0)
  • 2020-11-27 05:14
    function chunkArrToMultiDimArr(arr, size) {
    
        var newArray = [];
    
        while(arr.length > 0)
        {
          newArray.push(arr.slice(0, size));
          arr = arr.slice(size);
        }
    
      return newArray;
    }
    
    //example - call function
    chunkArrToMultiDimArr(["a", "b", "c", "d"], 2);
    
    0 讨论(0)
  • 2020-11-27 05:15

    You can use the Array.prototype.reduce function to do this in one line.

    ECMAScript 6 style:

    myArr.reduce((rows, key, index) => (index % 3 == 0 ? rows.push([key]) 
      : rows[rows.length-1].push(key)) && rows, []);
    

    "Normal" JavaScript:

    myArr.reduce(function (rows, key, index) { 
      return (index % 3 == 0 ? rows.push([key]) 
        : rows[rows.length-1].push(key)) && rows;
    }, []);
    

    You can change the 3 to whatever you want the number of columns to be, or better yet, put it in a reusable function:

    ECMAScript 6 style:

    const toMatrix = (arr, width) => 
        arr.reduce((rows, key, index) => (index % width == 0 ? rows.push([key]) 
          : rows[rows.length-1].push(key)) && rows, []);
    

    "Normal" JavaScript:

    function toMatrix(arr, width) {
      return arr.reduce(function (rows, key, index) { 
        return (index % width == 0 ? rows.push([key]) 
          : rows[rows.length-1].push(key)) && rows;
      }, []);
    }
    
    0 讨论(0)
提交回复
热议问题