-1

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);
HelloWorld
  • 133
  • 1
  • 15
  • 1
    your functions are returning the array, not the number – nice ass Mar 31 '14 at 01:52
  • Where have you defined the function `number`? `ReferenceError: number is not defined` [Learn how to](http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820) [**debug** JavaScript](https://developers.google.com/chrome-developer-tools/docs/javascript-debugging). – Felix Kling Mar 31 '14 at 01:52
  • 1
    Look very carefully at the sense of your comparisons in this function: `function max (markArr)` –  Mar 31 '14 at 01:53
  • This is a better approach. http://stackoverflow.com/questions/1669190/javascript-min-max-array-values/1669222#1669222 – aljordan82 Mar 31 '14 at 01:57
  • I think this number function you are using doesn't exist. If you are trying to convert it to a number, use parseFloat() – Pablo S G Pacheco Mar 31 '14 at 01:59

1 Answers1

0

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

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194