Reputation: 1
So this the function code i came up with I do not know what is wrong with it. It keeps giving 0 as my code.
function minValue(array) {
let min = 0;
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[i].length; j++) {
if (array[j][i] == "string") {
min = Math.min(min, parseInt(array[j][i]));
} else {
min = Math.min(min, array[j][i]);
}
}
}
return min;
}
let matrix = [
[57, 71, 37, 99, 62, '83', '95', '54', 38, 25],
[8, 64, 100, '51', 43, 21, 21, 33, 11, 43],
[67, 25, 45, 67, 88, 72, 74, 77, 53, 38]
];
console.log(minValue(matrix));
I keep on getting 0 as my answer.
Upvotes: 0
Views: 48
Reputation: 192262
Your function doesn't work because you use 0
as the initial value, and it's smaller than all other values. Use Infinity
as the initial value.
Note: you've switch between i
and j
here - array[j][i]
. I would also remove the condition, and always convert to number (I've used the +
operator here).
function minValue(array) {
let min = Infinity;
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[i].length; j++) {
min = Math.min(min, +array[i][j]);
}
}
return min;
}
const matrix = [
[57, 71, 37, 99, 62, '83', '95', '54', 38, 25],
[8, 64, 100, '51', 43, 21, 21, 33, 11, 43],
[67, 25, 45, 67, 88, 72, 74, 77, 53, 38]
];
console.log(minValue(matrix));
Another options is to flatten matrix to a single array, map all items to numbers, and spread into Math.min()
:
const minValue = array => Math.min(...array.flat().map(Number));
const matrix = [
[57, 71, 37, 99, 62, '83', '95', '54', 38, 25],
[8, 64, 100, '51', 43, 21, 21, 33, 11, 43],
[67, 25, 45, 67, 88, 72, 74, 77, 53, 38]
];
console.log(minValue(matrix));
Upvotes: 1