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
You can use Array.from() with a
length
parameter to automatically create arrays and populate them with the 2ndmapFn
parameter.Use the
index
parameters passed to themapFn
to walk thepopulateArr
and fill values, falling back to0
once you exhaust those available.Adapting an answer from here to split the source array into chunks like the PHP
array_chunk
function