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

后端 未结 15 1796
独厮守ぢ
独厮守ぢ 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:11

    This code is generic no need to worry about size and array, works universally

      function TwoDimensional(arr, size) 
        {
          var res = []; 
          for(var i=0;i < arr.length;i = i+size)
          res.push(arr.slice(i,i+size));
          return res;
        }
    
    1. Defining empty array.
    2. Iterate according to the size so we will get specified chunk.That's why I am incrementing i with size, because size can be 2,3,4,5,6......
    3. Here, first I am slicing from i to (i+size) and then I am pushing it to empty array res.
    4. Return the two-dimensional array.

提交回复
热议问题