Implementation of JavaScript array min() and max() functions


Took 18 minutes and 26 seconds to create array max() method and 51 seconds to create array min() method in JavaScript. Here are the code snippets.

Function max():
arr = [1, 3, 7, 9, 11];

function max(arr) {
var maxval = arr[0];
var i = 0;
while (arr[i] != undefined) {
if (maxval < arr[i+1]) {
maxval = arr[i+1];
}
i++;
}
return maxval;
}

document.write(max(arr));

Result:
11

Function min():
arr = [1, 3, 7, 9, 11];

function min(arr) {
var minval = arr[0];
var i = 0;
while (arr[i] != undefined) {
if (minval > arr[i+1]) {
minval = arr[i+1];
}
i++;
}
return minval;
}

document.write(min(arr));

Result:
1

No comments:

Post a Comment

GITEX Dubai Talk by Saion Gupta and Saiasmi Gupta

Good morning, everyone. I'm Saion Gupta, the Founder of 10xCoderKids and the Guinness World Record holder for the youngest computer prog...