function findMin(array) {
return Math.min.apply(Math, array);
}
function rearrange(matrix) {
let min = 0;
let newMatrix = [];
for (let i = 0; i < matrix.length; i++) {
let min = findMin(matrix[i]);
newMatrix[i].push(min);
}
return newMatrix;
}
Example input:
let matrix = [[2,7,1],
[0,2,0],
[1,3,1]]
rearrange(matrix);
Log:
Uncaught TypeError: Cannot read property 'push' of undefined
at reArrange (test.js:11)
at test.js:23
I'm trying to have the nested arrays sorted in an increasing order. If I didn't get it wrong, it doesn't happen because newMatrix[i] is not defined. But can't JS just create it and push the element? Do we need an extra step prior to doing this? Could you please suggest me another way, if this method won't work?
newMatrixis your array. You are trying to push in theith element of your array, which isundefined