简体   繁体   中英

Javascript - creating a function with two arguments and returning 2d array

I need to write a function which takes two arguments - rows and columns. The purpose of this function is returning 2d array with given numbers and rows. I need to return the array by using the function. Here's a code:

I'm a beginner and every feedback will be strongly appreciated. :-)

I've checked StackOverflow, I've tried to google it, check appropriate websites - unfortunately, no luck

function create2Darray(A) {
            var columns = [];
            var rows = Math.sqrt(A.length);
            for (var i = 0; i < rows; i++) {
                  columns[i] = [];
                  for (var j = 0; j < rows; j++) {
                        columns[i][j] = A[i * rows + j];
                  }
            }
            return columns;
      }

You could use Array.from with an object with the length and map with the second parameter the inner arrays.

 const getArray = (l, w) => Array.from({ length: l }, (_, i) => Array.from({ length: w }, (_, j) => i * w + j)); console.log(getArray(3, 2));
 .as-console-wrapper { max-height: 100% !important; top: 0; }

Your question statement doesn't match the code you tried. It seems you want to convert single dimensional array to 2D array. Your code is fine. But the problem is that Math.sqrt(A.length); may return float and i * rows + j will become float and array don't have float indexes . Just use Math.ceil() to fix

 function create2Darray(A) { var columns = []; var rows = Math.ceil(Math.sqrt(A.length)); for (var i = 0; i < rows; i++) { columns[i] = []; for (var j = 0; j < rows; j++) { columns[i][j] = A[i * rows + j]; } } return columns; } console.log(create2Darray([1,2,3,4,5,6,7,8]))

The following two solution are for function which takes length and width.

 function array(l,w){ let res = []; for(let i = 0; i < l;i++){ res[i] = []; for(let j = 0; j < w; j++){ res[i][j] = (w * i) + j } } return res; } console.log(JSON.strigify(array(3,2)))

A on liner can be made using nested map()

 const array = (l,w) => [...Array(l)].map((x,i) => [...Array(w)].map((x,j) => (i*w) + j)) console.log(JSON.stringify(array(3,2)))

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