Vijaykarthik
Vijaykarthik

Reputation: 333

How to calculate average of 5 student mark, and implement that in datatable.js, how to do this?

This is my json data

var myList = [
    [1, "Karthick", 90, 95, 85, 95, 100,],
    [2, "Ram", 98, 90, 95, 95, 100],
    [3, "Suthan", 80, 90, 85, 100, 95],
    [4, "Ganesh", 90, 100, 100, 99, 96],
    [5, "Thilak", 98, 99, 99, 100, 100],
    [6, "Mari",90, 100, 100, 99, 100]
]; 

$(document).ready(function() {
    $('#demo').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' ); 
    $('#example').dataTable( {
        "data": myList,
        "columns": [
            { "title": "Id" },
            { "title": "Name" },
            { "title": "Mark1" },
            { "title": "Mark2"},
            { "title": "Mark3"},
            { "title": "Mark4"},
            { "title": "Mark5"},
            { "title": "Average"},
            { "title": "Grade"}
        ]
    });   
});

I send those json data in to datatable.js, but my doubt is how to calculate the average of 5 marks and show that average mark in datatable using datatable.js

Upvotes: 0

Views: 1509

Answers (2)

user3923043
user3923043

Reputation:

Here is the soln.

var myList = [
    [1, "Karthick", 90, 95, 85, 95, 100,],
    [2, "Ram", 98, 90, 95, 95, 100],
    [3, "Suthan", 80, 90, 85, 100, 95],
    [4, "Ganesh", 90, 100, 100, 99, 96],
    [5, "Thilak", 98, 99, 99, 100, 100],
    [6, "Mari",90, 100, 100, 99, 100]
]; 

   function avg( ){
    var i, av = 0;
    for (i = 2, len = this.length ; i < len; i++)
    {
        if(!isNaN(this[i]))
        av += this[i];
    }
    return av;
}
Array.prototype.avg = avg; 

    myList.map(function(array){
    array[array.length-1] = array.avg();
          return array;
    });

Upvotes: 1

Carl
Carl

Reputation: 1816

Something like this before the ('#example').dataTable(

 for(var i in myList){
      // Assuming they are all out of 100
       var avg = (( myList[i][2]+myList[i][3]+myList[i][4]+myList[i][5]+myList[i][6] ) / 5);
      // add avg to array
      myList[i].push(avg);
      // add grade
      myList[i].push("Some logic to put number here");
 }

Basically all the above would do is calculate the avg (and the grade with whatever logic), then stick the info on the end of the array items in myList, ready to be passed straight in to the dataTable.

Edit: see working example in jsfiddle http://jsfiddle.net/w5bqxops/1/

FYI: seems your also missing a closing }); for the jquery ready :)

Upvotes: 0

Related Questions