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

Coding for Kids

What is coding? In coding we build a program to do a specific task for us. Code: A code is a set of computer instructions and when you will ...