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

后端 未结 15 1793
独厮守ぢ
独厮守ぢ 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 04:56

    Short answer use:

    const gridArray=(a,b)=>{const d=[];return a.forEach((e,f)=>{const 
    h=Math.floor(f/b);d[h]=d[h]||[],d[h][f%b]=a[f]}),d};
    

    Where:

    a: is the array
    b: is the number of columns
    

    Long answer you can read the article:

    How to convert an array of length ‘n’ to array grid

提交回复
热议问题