+ 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
7 Answers
+ 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
+ 2
Thank you everyone for your help!
+ 1
Ahh i see that now, nice work de do
0
on line 11, you can't return max and min like that
try this instead
return { max, min };
0
Hi Phurinat,
I tried that, but doesn't seem to be working :(
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]));
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.