简体   繁体   中英

I have no Idea why is my min function not working it keeps on giving me 0 as an answer

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.

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));

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