skip to Main Content

I wrote a function that creates such a Multi-Dimensional array(2D matrix) with zeros, and then tried to replace zeros in this matrix with digits of populateArr[ … ] writinga new function ,but nothing worked.

WHAT I NEED ↓↓↓
I need to write a function that replace the zeros in this matrix with numbers of "populateArr[ … ]" array.

I should get 
[1,4,6],
[9,25,43],
[12,8,3],
[10,56,72],
[23,14,66],
]
[ [ 1, 4, 6 ], [ 9, 25, 43 ], [ 12, 8, 3 ], [ 10, 56, 72 ], [ 23, 14, 66 ] ]  with numbers from let populateArr = [1, 4, 6, 9, 25, 43, 12, 8, 3, 10, 56, 72, 23, 14, 66];

Thank You in advance.

First I tried using Array.prototype.fill(), but nothing worked, then I wrote another function, but it also does not work. work, I still don’t understand how to populate this array.

Here Im sharing my code.

function createMatrix(rows, cols) {
    let arr = [];
    let result = '';
    for (let rowIndex = 0; rowIndex <= rows; rowIndex++) {
            let column = [];
             for (let colIndex = 0; colIndex < cols; colIndex++) {
                column.push(0);
            }
            result += `[${column}], n`;
            arr.push(column);
        console.log(populateMatrix(rows, cols)); 
        }
        
        result += ']';
        console.log(result);
        return arr;
}
console.log(createMatrix(4, 3));

function populateMatrix(rows, cols) {
    let populateArr = [1, 4, 6 , 9, 25, 43, 12, 8, 3, 10, 56, 72, 23, 14, 66];
   let populated =  createMatrix.push(populateArr);
   console.log(populated);
}

2

Answers


  1. You can use Array.from() with a length parameter to automatically create arrays and populate them with the 2nd mapFn parameter.

    Use the index parameters passed to the mapFn to walk the populateArr and fill values, falling back to 0 once you exhaust those available.

    const createMatrix = (rows, cols, fill) =>
      Array.from({ length: rows }, (_, row) =>
        Array.from({ length: cols }, (_, col) => fill[row * cols + col] ?? 0),
      );
    
    const populateArr = [1, 4, 6, 9, 25, 43, 12, 8, 3, 10, 56, 72, 23, 14, 66];
    console.log(createMatrix(5, 3, populateArr));
    .as-console-wrapper { max-height: 100% !important; }
    Login or Signup to reply.
  2. Adapting an answer from here to split the source array into chunks like the PHP array_chunk function

    const createMatrix=(size=3,source=[])=>{
      return source.reduce((a,i,x)=>(a[x/size|0] ??=[] ).push(i) && a,[]);
    }
    
    let size=3;
    let numbers=[
      1, 4, 6,
      9, 25, 43,
      12, 8, 3,
      10, 56, 72,
      23, 14, 66
    ];
    let matrix=createMatrix( size, numbers );
    
    console.log( matrix )
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search