+ 1

Help me with this code - finding max and min value

Hello fellow coders, I'm trying to solve this problem, where I need to find max and min value from an array in JavaScript. I couldn't get the min value. Any idea what's wrong with the logic? Thanks! https://code.sololearn.com/WaIfVSPO731d

17th Sep 2019, 12:41 AM
Jojo
Jojo - avatar
7 Réponses
+ 4
You ate almost there: function findMaxMin (arr) { let max = arr[0]; let min = arr[0]; for ( let i=0; i< arr.length; i++) { if (arr[i] > max) { max = arr[i]; }; if (arr[i] < min) { min = arr[i]; } } return [max, min]; } document.write(findMaxMin([2,3,7,8,0,4])); 1. you have to return as array, if you return as () it will return only one value, 2. just returning will NOT print it, so you have to use document. write to print that result
17th Sep 2019, 4:53 AM
Dejan Dozet
Dejan Dozet - avatar
+ 2
Thank you everyone for your help!
17th Sep 2019, 5:02 AM
Jojo
Jojo - avatar
+ 1
Ahh i see that now, nice work de do
17th Sep 2019, 4:58 AM
Anthony Johnson
Anthony Johnson - avatar
0
on line 11, you can't return max and min like that try this instead return { max, min };
17th Sep 2019, 1:01 AM
Phurinat Puekkham
Phurinat Puekkham - avatar
0
Hi Phurinat, I tried that, but doesn't seem to be working :(
17th Sep 2019, 1:12 AM
Jojo
Jojo - avatar
0
Did you want to display it to the screen or display in console.log ? if you want to display it to the screen, you have to access to the DOM. Example HTML <p id="min"></p> <p id="max"></p> Javascript let min = document.getElementById("min"); let max = document.getElelmentById("max"); var arr = [1, 2, 5]; var answer = findMaxMin(arr); min.innerHtml = answer.min; max.innerHtml = answer.max; or if you want to display it to the console console.log(findMaxMin([1, 6, 4, 8]));
17th Sep 2019, 1:43 AM
Phurinat Puekkham
Phurinat Puekkham - avatar
0
function findMaxMin (arr) { arr.sort(); min = arr[0]; max = arr[2]; alert(arr[0]); alert(arr[2]); } findMaxMin([8,3,6]); this should help you, you will have to modify it but you can see how the sort() method can be helpful.
17th Sep 2019, 2:47 AM
Anthony Johnson
Anthony Johnson - avatar