jquery function to sum vaules from a 10 line array and output to screen

I need to write a jquery function to take vaules from an array, add them together and output the answer to the screen. The array is created with 10 lines, each containing a name followed by 3 numbers, this is currently being output the screen. I need to change the output the the sum of the 3 numbers. So i need the function to go through each line of the array, add the numbers and output to screen.

var classdata = [];
var midterm1, midterm2, midterm3, final;

function setup() {
 classdata[0] = "Jane Doe,80,75,90,87";
 classdata[1] = "John Doe,70,65,60,70";
 classdata[2] = "Jack Smith,80,80,90,83";
 classdata[3] = "Jen Smith,90,70,60,75";
 classdata[4] = "Fred Ryan,90,90,86,80";
 classdata[5] = "Chris Martin,40,50,35,40";
 classdata[6] = "Fiona Rowe,50,30,45,45";
 classdata[7] = "Mike Smith,70,90,65,78";
 classdata[8] = "Mary Ryan,85,95,83,75";
 classdata[9] = "Jack Walsh,65,80,73,60";
}

function outputdata() {
 var output="";
 for (i in classdata)
 {
   output+=classdata[i]  + "\n";
 }
$('#resultdata').text(output);
}

Answers 1

  • What you want "Jane Doe 84 John Doe 68 Jack Smith 83" is not a valid sequence. There are no way to do this. You have to use one rule for every calculation.

    My calculation is based on "desired output is the average of the first two numbers out of 50 then the average of the 2nd 2 number out of 50, both added together to giver overall mark".

    HTML

    <span id="resultdata"></span>
    

    jQuery:

    output = "";
    var classdata = [];
    
    classdata[0] = "Jane Doe,80,75,90,87";
    classdata[1] = "John Doe,70,65,60,70";
    classdata[2] = "Jack Smith,80,80,90,83";
    classdata[3] = "Jen Smith,90,70,60,75";
    classdata[4] = "Fred Ryan,90,90,86,80";
    classdata[5] = "Chris Martin,40,50,35,40";
    classdata[6] = "Fiona Rowe,50,30,45,45";
    classdata[7] = "Mike Smith,70,90,65,78";
    classdata[8] = "Mary Ryan,85,95,83,75";
    classdata[9] = "Jack Walsh,65,80,73,60";
    
    for (i = 0; i < classdata.length; i++){
        a = classdata[i].split(",");
      sum1 = 0;
      sum2 = 0;
      for(j = 1; j <= 4; j++){
        if(j < 3)
            sum1 = sum1 + parseInt(a[j]);
        else
          sum2 = sum2 + parseInt(a[j]);
      }
      s = Math.ceil(sum1/2) + Math.ceil(sum2/2);
      output += a[0] + " => " + Math.ceil(s/2) + "<br/>";  
    }
    $('#resultdata').html(output);
    

    Output:

    Jane Doe => 84
    John Doe => 67
    Jack Smith => 84
    Jen Smith => 74
    Fred Ryan => 87
    Chris Martin => 42
    Fiona Rowe => 43
    Mike Smith => 76
    Mary Ryan => 85
    Jack Walsh => 70
    

    Let me know if you have any rule for it or not, try this and give the feedback.


Related Articles