Link to home
Start Free TrialLog in
Avatar of Robert Barbeto
Robert Barbeto

asked on

Calculating Average in Node.JS

Hello Experts,

Need to calculate the average of the row in Node.JS to be stored in the Average Data

So far I have attempted to do the following after the first row.week1 data-field

+(row.week1+row.week2+row.week3+row.week4)/4

I have removed this line in the code as it has caused the script to break.

Here is the code:
//Following is basic configuration for Node.JS
var express = require('express');
var app = express();
var mysql= require('mysql');
//Line 6 createsthe connection between the mysql database. 
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '-------',
  database : 'databasetable'
});
//Getsthe information from either .html or node.js file. 
//Standard configuration
app.get('/', function (req,res) {
  connection.query('select * from storebenefit', function (error, results, fields){
    if (error) throw error;
	var reply='';
	//Object.keys() method returns an array of a given object's own property name
	//Callback to reply. access rows using index and columns using dot operator. 
	 reply+="<h2><table border='1'><tr>"
	 reply+="<td>No</td>"
	 reply+="<td>StoreName</td>"
	reply+="<td>Week1</td>"
	reply+="<td>Week2</td>"
	reply+="<td>Week3</td>"
	reply+="<td>Week4</td>"
	reply+="<td>Average</td></tr>"
	Object.keys(results).forEach(function(key){
		//For each loop passing results variable through the Object.Keys method.
		//Header of Table		
		var row= results[key];
		reply+="<tr><td>"+row.No+"</td><td>"+row.StoreName+"</td><td>"+row.Week1+"</td><td>"+row.Week2+"</td><td>"+row.Week3+"</td><td>"+row.Week4+"</td></tr>";
	

  });
  reply += "</table>"
  	res.send(reply);
});
});
app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

What error are you getting?
I am guessing it has to do with dividing a string by a value.

Your row values are being interpreted as strings so your division is failing.

Two ways to change it
1. Multiply each value by 1
(row.week1*1+row.week2*1+row.week3*1+row.week4*1)/4

Open in new window

2. Use parseInt()
(parseInt(row.week1)+parseInt(row.week2)+parseInt(row.week3)+parseInt(row.week4))/4

Open in new window

You could also do this in your SQL query and then just retrieve the value in code

SELECT (week1+week2+week3+week4)/4 AS `Average`, `sb`.* FROM `storebenefit` `sb`

Open in new window

Avatar of Robert Barbeto
Robert Barbeto

ASKER

Hello Expert,

I have followed your advice and have attempted to insert the code as the following:

var express = require('express');
var app = express();
var mysql= require('mysql');

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'password',
  database : 'nodeTest'
});
//Getsthe information from either .html or node.js file. 
app.get('/', function (req,res) {
  connection.query('select * from storebenefit', function (error, results, fields){
    if (error) throw error;
	var reply='';
	reply+="<h2><table border='1'bgcolor=#ddeeff><tr>"
	reply+="<th>No</th>"
	reply+="<th>StoreName</th>"
	reply+="<th>Week1</th>"
	reply+="<th>Week2</th>"
	reply+="<th>Week3</th>"
	reply+="<th>Week4</th>"
	reply+="<th>Average</th></tr>"
	Object.keys(results).forEach(function(key){
		//For each loop passing results variable through the Object.Keys method.
		//Header of Table		
		var row= results[key];
		reply+="<tr><td>"+row.No+"</td><td>"+row.StoreName+"</td><td>"+row.Week1+(row.week1*1+row.week2*1+row.week3*1+row.week4*1)/4=+row.Average+"</td><td>"+row.Week2+"</td><td>"+row.Week3+"</td><td>"+row.Week4+"</td></tr>";
	

  });
  reply += "</table>"
  	res.send(reply);
});
});
app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

Open in new window


As of now, the Average table is currently sitting blank with no values inside of it for each row. I have tried adding the Average as /4=+Average+ but have gotten a Left-Hand error. How do I designate the averaged data into the Average cell so that it shows?
You could also look into the Math.js library located here.  It is overkill for a single function, but you may find other uses, as well.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hello Expert,

I have taken your advice and have updated the code with the following which is current. The Arithmetic has been added but now it needs to show in Average row column for each row. The Average column is on the very end of the table. The first suggestion is good as the table is supposed to display in the browser.

//Following is basic configuration for Node.JS
var express = require('express');
var app = express();
var mysql= require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '---',
  database : '-----'
});
app.get('/', function (req,res) {
  connection.query('select * from storebenefit', function (error, results, fields){
    if (error) throw error;
	var reply='';
	
	reply+="<h2><table border='1'bgcolor=#ddeeff><tr>"
	reply+="<th>No</th>"
	reply+="<th>StoreName</th>"
	reply+="<th>Week1</th>"
	reply+="<th>Week2</th>"
	reply+="<th>Week3</th>"
	reply+="<th>Week4</th>"
	reply+="<th>Average</th></tr>"
	Object.keys(results).forEach(function(key){
		var row= results[key];
		reply+="<tr><td>"+row.No+"</td><td>"+row.StoreName+"</td><td>"+row.Week1+(row.week1*1+row.week2*1+row.week3*1+row.week4*1)/4+"</td><td>"+row.Week2+(row.week1*1+row.week2*1+row.week3*1+row.week4*1)/4+"</td><td>"+row.Week3+(row.week1*1+row.week2*1+row.week3*1+row.week4*1)/4+"</td><td>"+row.Week4+(row.week1*1+row.week2*1+row.week3*1+row.week4*1)/4+"</td></tr>";
  });
  reply += "</table>"
  	res.send(reply);
});
});
app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

Open in new window


While there are currently no issues in the cmd console, there is no values transferred over to the Average Column rows.

Edit: I have recently attempted the following second and third suggestion but got an Unexpected Input error issue with both lines.
Edit: I have recently attempted the following second and third suggestion but got an Unexpected Input error issue with both lines.
If you are going to mention errors please post the error so that we can see what it is along with the code that caused it - otherwise this does not help us help you.

Onto your code - I don't see anywhere where you have implemented the suggestions recommended

Secondly, it seems you are trying to add the average to each cell - which makes no sense to me what is it this is meant to do
+row.Week1+(row.week1*1+row.week2*1+row.week3*1+row.week4*1)/4+

Open in new window

You are mixing concatenation with aritmetic - this is going to cause confusion
This is common
(row.week1*1+row.week2*1+row.week3*1+row.week4*1)/4

Open in new window

Rather take it out and put it in a variable.

Please show us a sample of what you want the output to look like.
Hello Experts,

I have solved the issue by adding .ToFixed(2) to the end of each row.week variable. Also, by adding the (row.week*row.week2*row.week3*row.week4)/4 to the very end has also solved the arithmetic issue.