简体   繁体   中英

How to change array into (m x n) array

How to change an array (vector) for instance [1, 2,...,16] into [[1,2,3,4],..., [13, 14, 15, 16]] . I wrote

function IntoMatrix(m,n, array){
temp = [];
Temp = [];
for (j=0; j<array.length; j+=m){
  for (i=0; i<n; i++){
   temp.push(array[i+j]);
    }
    Temp.push(temp);
  }
  return Temp;
}

but for sure something is wrong. Do you think that I should use concat instead of push method in Temp ?

For every internal for loop, you need to reset temp=[] .

 function IntoMatrix(m,n, array){ temp = []; Temp = []; for (j=0; j<array.length; j+=m){ temp = []; for (i=0; i<n; i++){ temp.push(array[i+j]); } Temp.push(temp); } return Temp; } console.log(IntoMatrix(4,4,[1,2,3,4,5,6,7,8]));

It's not clear what a function that takes both m and n should do if m * n is not equal to the length of the original array. For example, asking for a 5x10 matrix from an array of 16 elements makes no sense.

Since n is dependent on m and arr.length , I would suggest just taking the inner length ( m ) and outputting the rows that fit. You can do this with a single loop and slice :

 let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] function matrix(arr, m){ let res = [] for (let i = 0; i<arr.length; i+=m){ res.push(arr.slice(i, i+m)) } return res } console.log(matrix(arr, 4)) // 4 * 4 console.log(matrix(arr, 2)) // 2 * 8

You can use reduce to push cells onto row arrays and rows onto the result array. Row size is determined by the square root of the length of the input by default argument and can be adjusted.

It's not clear that two number parameters are necessary; one parameter to specify row size is sufficient.

 const toMatrix = (a, n=a.length**0.5) => a.reduce((m, e, i) => { if (i % n === 0) { m.push([]); } m[m.length-1].push(e); return m; }, []) ; console.log(toMatrix([...Array(16).keys()].map(e => ++e))); console.log(toMatrix([...Array(9).keys()].map(e => ++e)));

You could use Array.from method and get the element with current value of cols * i + j

 function IntoMatrix(rows, cols, array) { return Array.from(Array(rows), (e, i) => { return Array.from(Array(cols), (el, j) => { return array[cols * i + j] }) }) } const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] console.log(JSON.stringify(IntoMatrix(3, 4, arr))) console.log(JSON.stringify(IntoMatrix(4, 5, arr)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM