Question

hello i have an array and i cant seem to get the minimum and maximum value of it idk what is wrong here is my code

    var repeat, studentArr = [], markArr = [];
while (repeat !== 'n' && repeat !== 'N'){
    studentArr.push(prompt("Enter Student Name: "));
    markArr.push(parseInt (prompt("Enter Student mark: ")));
    repeat = prompt ("Do you want to enter another student: y/n");
}  

function min (markArr){
    var min = Number.Max_Value;
    for(var i = 0; i < markArr.length; i++){
       if(number(markArr[i]) < min)
           min = number(markArr[i]); 
    }
    return markArr;
}
var smallest = min(markArr);

function max (markArr){
    var max = Number.Max_Value;
    for(var i = 0; i > markArr.length; i++){
       if(number(markArr[i]) < max)
           max = number(markArr[i]); 
    }
    return markArr;
}
var largest = max(markArr);

    document.write(largest);
Was it helpful?

Solution

You could extend the Array type from Javascript, for sample:

Array.prototype.min = function(comparer) {

    if (this.length === 0) return null;
    if (this.length === 1) return this[0];

    comparer = (comparer || Math.min);

    var result = this[0];
    for (var i = 1; i < this.length; i++)
        result = comparer(this[i], v);  

    return result;
}

Array.prototype.max = function(comparer) {

    if (this.length === 0) return null;
    if (this.length === 1) return this[0];

    comparer = (comparer || Math.max);

    var result = this[0];
    for (var i = 1; i < this.length; i++)
        result = comparer(this[i], v);    

    return result;
}

And use something like this:

var minValue = yourArray.min();
var maxValue = yourArray.max();

Look the jsbin: http://jsbin.com/yoyecono/1/edit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top