Generating a price per item in an html table using a javascript - javascript

I have a javascript that is generating a table for me. The elements in the table are gathered in an array of arrays called sep. Sep contains 1152 sub arrays that are of the form:
Sep[0] //["316SS", "K", "-100 to 225°C", "Brass", "1/8", "4'", "4'", "8", "Ungrounded"]
So basically there are 1152 rows, each of which defines a products with 9 parameters. I want to make a for-loop that will create a price for each of the configurations. This is what I have so far:
//PART 1-------------WORKS FINE-----------------------------------
var eopartprice2 = []; //matrix that I want to contain my prices
for (var i = 0; i < sep.length; i++) {
strnum1 = sep[i][5]; //parameter 5 is a length of material
len1 = Number(strnum1.substr(0, strnum1.length - 1));
strnum2 = sep[i][6]; //parameter 6 is another length of material
len2 = Number(strnum2.substr(0, strnum2.length - 1));
strnum3 = sep[i][7]; //parameter 7 is the number of units required
condnum = Number(strnum3.substr(0, strnum3.length));
feetOfMat = len1*len2*condnum; //The product of these is the total feet of req material
//PART 2------------PFCost always = 0.87--------------------------
//Next i need to identify the cost of the material (to multiply by the total feet)
var costOfMat = [0.87, 0.87, 1.77, 0.55] //different costs of the 4 materials
if (sep[i][0] = "304SS") {
var PFCost = costOfMat[0]; //304SS costs 0.87/foot
} else if (sep[i][0] = "316SS") {
var PFCost = costOfMat[1]; //316SS costs 0.87/foot
} else if (sep[i][0] = "Inconel") {
var PFCost = costOfMat[2]; //Inconel costs 1.77/foot
} else if (sep[i][0] = "High Temp. Glass") {
var PFCost = costOfMat[3]; //High Temp. Glass costs 0.55/foot
}
baseMatCost[i] = PFCost*feetOfMat; //I'd like to generate a matrix that
//contains all of the base prices (1 for each row)
//PART 3---------------fitcost always = 36------------------------
//Trying to identify the cost of brass vs. stainless fittings
if (sep[i][3] = "Brass") {
fitcost = 36;
} else if (sep[i][3] = "Stainless Steel") {
fitcost = 37;
}
}
My Problem so far is that I want the prices to be defined based off of whether or not the if statements are satisfied but in both cases (fitcost and PFCost) the values are simply the ones defined in the first if statement.
Lastly I'd like to generate my final price in the eopartprice2 matrix based off adding up the materials generated above + some cost of labor multiplied by some margin.
Also I'm concerned with the speed of how quickly this runs as it will be a live table in my website, and every time I add more to this I feel like it's taking longer and longer to generate. Here's a link to my w3 that I'm working in.
Please, any help would be greatly appreciated :)

In your if statement conditions, you're using a single equals sign. This is an assignment operator, not a comparison operator!
So, an if statement such as if (sep[i][0] = "304SS") is actually assigning the value "304SS"; it is not comparing the value "304SS" to sep[i][0].
To correctly compare the values, you'll want to change the single equals sign to a double equals:
if (sep[i][0] == "304SS").
Note: == will convert types if necessary before comparing. For example: ".87" == 0.87 returns true.

Related

Transform CSV into an Array of Objects

I have a CSV file like this one below, I must take some different values from it, but I'm struggling in transform this CSV into an array of Objects
"+++++++++ 1.2 LifeTime Cost and Emissions +++++++++","<TABLE>"
" ","year1","year2","year3","year4","year5","year6","year7","year8","year9","year10","year11","year12","year13","year14","year15","year16","year17","year18","year19","year20","year21","year22","year23","year24","year25","<HEADER>"
"Total Annual Energy Costs (incl. annualized capital costs and electricity sales) ($)",-560.9845,353.4204,451.6855,514.2567,523.2091,572.8177,622.6726,632.3996,642.4129,652.7211,663.3330,674.2575,1458.1040,617.1780,661.0587,692.5061,705.1385,732.5260,760.2972,774.0806,788.2706,802.8795,817.9194,833.4033,849.3444
"Total Annual CO2 emissions (kg)",387734.0330,387734.0330,387736.8925,387736.8925,387736.8925,387738.4191,387738.4191,387738.4191,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886
"Levelized Cost Of Energy ($/kWh)",-0.1738,0.1095,0.1404,0.1598,0.1626,0.1786,0.1942,0.1972,0.2003,0.2035,0.2069,0.2103,0.4547,0.1925,0.2061,0.2159,0.2199,0.2284,0.2371,0.2414,0.2458,0.2504,0.2551,0.2599,0.2649
I've tryed this:
const csvFilePath = 'Result_Lifetime002.csv';
const json = await csvToJson().fromFile(csvFilePath);
const jsonString = JSON.stringify(json, null, 2);
But it returns a big string with an array in it.
Anyway, the expected result should be something like this (just taking the item 1.2 as an example):
const result = [
{
"+++++++++ 1.2 LifeTime Cost and Emissions +++++++++":"Total Annual Energy Costs (incl. annualized capital costs and electricity sales) ($)",
"year1": -560.9845,
"year2": 353.4204,
"year3": 451.6855,
"year4": 514.2567,
"year5": 523.2091,
"year6": 572.8177,
"year7": 622.6726,
"year8": 632.3996,
"year9": 642.4129,
"year10": 652.7211,
"year11": 663.3330,
"year12": 674.2575,
"year13": 1458.1040,
"year14": 617.1780,
"year15": 661.0587,
"year16": 692.5061,
"year17": 705.1385,
"year18": 732.5260,
"year19": 760.2972,
"year20": 774.0806,
"year21": 788.2706,
"year22": 802.8795,
"year23": 817.9194,
"year24": 833.4033,
"year25": 849.3444
},
{
"+++++++++ 1.2 LifeTime Cost and Emissions +++++++++":"Total Annual CO2 emissions (kg)",
"year1": 387734.0330,
"year2": 387734.0330,
"year3": 387736.8925,
"year4": 387736.8925,
"year5": 387736.8925,
"year6": 387738.4191,
"year7": 387738.4191,
"year8": 387738.4191,
"year9": 387738.8886,
"year10": 387738.8886,
"year11": 387738.8886,
"year12": 387738.8886,
"year13": 387738.8886,
"year14": 387738.8886,
"year15": 387738.8886,
"year16": 387738.8886,
"year17": 387738.8886,
"year18": 387738.8886,
"year19": 387738.8886,
"year20": 387738.8886,
"year21": 387738.8886,
"year22": 387738.8886,
"year23": 387738.8886,
"year24": 387738.8886,
"year25": 387738.8886,
},
{
"+++++++++ 1.2 LifeTime Cost and Emissions +++++++++":"Levelized Cost Of Energy ($/kWh)",
"year1": -0.1738,
"year2": 0.1095,
"year3": 0.1404,
"year4": 0.1598,
"year5": 0.1626,
"year6": 0.1786,
"year7": 0.1942,
"year8": 0.1972,
"year9": 0.2003,
"year10": 0.2035,
"year11": 0.2069,
"year12": 0.2103,
"year13": 0.4547,
"year14": 0.1925,
"year15": 0.2061,
"year16": 0.2159,
"year17": 0.2199,
"year18": 0.2284,
"year19": 0.2371,
"year20": 0.2414,
"year21": 0.2458,
"year22": 0.2504,
"year23": 0.2551,
"year24": 0.2599,
"year25": 0.2649
}
]
Would something like this work for you?
For simplicity's sake, I've placed the contents of your CSV inside a variable, and skipped the steps of reading the file (I'll give this code at very end). Please note that there are most likely more optimal ways of dealing with this, but I decided on going with this solution, since I could break it down into simple steps.
var data = `
+++++++++ 1.2 LifeTime Cost and Emissions +++++++++,<TABLE>
,year1,year2,year3,year4,year5,year6,year7,year8,year9,year10,year11,year12,year13,year14,year15,year16,year17,year18,year19,year20,year21,year22,year23,year24,year25,<HEADER>
Total Annual Energy Costs (incl. annualized capital costs and electricity sales) ($),-560.9845,353.4204,451.6855,514.2567,523.2091,572.8177,622.6726,632.3996,642.4129,652.7211,663.3330,674.2575,1458.1040,617.1780,661.0587,692.5061,705.1385,732.5260,760.2972,774.0806,788.2706,802.8795,817.9194,833.4033,849.3444
Total Annual CO2 emissions (kg),387734.0330,387734.0330,387736.8925,387736.8925,387736.8925,387738.4191,387738.4191,387738.4191,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886,387738.8886
Levelized Cost Of Energy ($/kWh),-0.1738,0.1095,0.1404,0.1598,0.1626,0.1786,0.1942,0.1972,0.2003,0.2035,0.2069,0.2103,0.4547,0.1925,0.2061,0.2159,0.2199,0.2284,0.2371,0.2414,0.2458,0.2504,0.2551,0.2599,0.2649
`;
// Create an array by splitting the CSV by newline
data = data.trim().split(/\r?\n/);
// Extract the first index, since we want to repeat it later on as
// the first key of every JSON element of your resulting array
// This is the long string with the pluses
/* remove this multiline comment to see the contents of data[0]
console.log(data[0]);
*/
var title = data[0].split(",")[0];
// Extract the other main keys - years
var innerKeys = data[1].trim().split(",");
// Remove the the last one, since we don't need it - <HEADER>
innerKeys.pop();
// Prepare the array for our results
var results = [];
// Loop through indivdual rows, and split by comma / ,
// We'll skip the first two, since we've dealt with them
// data[0] being the row with the long string with the pluses
// and data[1] being the row containing the years
for(var i = 2; i < data.length; i++) {
// Let's clean any trailing empty characters
var tempRow = data[i].trim();
// If there's anything we can work with
if(tempRow) {
// Create an array from the values in the current line
tempRow = tempRow.split(",");
// Let's get the value for our first keys
// These are the Total Annual etc strings from your CSV
var tempTitle = tempRow[0];
// Let's declare and fill our temp object
var innerJSON = {};
// The first key is the one with the pluses
// and its value is the Total Annual etc string
innerJSON[title] = tempTitle;
for(var j = 1; j < tempRow.length; j++) {
// Let's fill the years and give them matching values
innerJSON[innerKeys[j]] = tempRow[j];
}
// All done, add it to the resulting array
results.push(innerJSON);
}
}
console.log(results);
Now, if we were to read the contents of the data variable from you CSV, using FileReader object would do the trick. You could implement it like this.
var data = "";
var reader = new FileReader();
// I'm assuming you have an input element, whose type is file
// and that you read from it
reader = readAsText(document.getElementById("myFileInput").files[0]);
reader.addEventListener('load',function() {
data = reader.result;
parseData(data);
});
where parseData(data) would be a function doing all of the things shown in the first part of my answer (splitting your CSV into an array, looping, etc). Try it out below.
const file = document.getElementById("file");
const parse = document.getElementById("parse");
var data = "";
parse.addEventListener("click", readFile);
function readFile() {
let reader = new FileReader();
reader.readAsText(file.files[0]);
reader.addEventListener('load', function(e) {
data = reader.result;
parseData(data);
});
}
function parseData(data) {
// Let's remove the quotes first - you don't have to do this
// if it's absolutely necessary to keep them
data = data.replaceAll("\"","");
// Create an array by splitting the CSV by newline
data = data.trim().split(/\r?\n/);
// Extract the first index, since we want to repeat it later on as
// the first key of every JSON element of your resulting array
// This is the long string with the pluses
/* remove this multiline comment to see the contents of data[0]
console.log(data[0]);
*/
var title = data[0].split(",")[0];
// Extract the other main keys - years
var innerKeys = data[1].trim().split(",");
// Remove the the last one, since we don't need it - <HEADER>
innerKeys.pop();
// Prepare the array for our results
var results = [];
// Loop through indivdual rows, and split by comma / ,
// We'll skip the first two, since we've dealt with them
// data[0] being the row with the long string with the pluses
// and data[1] being the row containing the years
for(var i = 2; i < data.length; i++) {
// Let's clean any trailing empty characters
var tempRow = data[i].trim();
// If there's anything we can work with
if(tempRow) {
// Create an array from the values in the current line
tempRow = tempRow.split(",");
// Let's get the value for our first keys
// These are the Total Annual etc strings from your CSV
var tempTitle = tempRow[0];
// Let's declare and fill our temp object
var innerJSON = {};
// The first key is the one with the pluses
// and its value is the Total Annual etc string
innerJSON[title] = tempTitle;
for(var j = 1; j < tempRow.length; j++) {
// Let's fill the years and give them matching values
innerJSON[innerKeys[j]] = tempRow[j];
}
// All done, add it to the resulting array
results.push(innerJSON);
}
}
console.log(results);
}
<input type="file" id="file">
<button type="button" id="parse">Parse</button>

Iterating thorugh array but always returning last value

I am iterating thorugh an array and trying to get different data for each object in array but I end up with same data, if i have three products in billBodies i end up with three item that have the same value (for example i have 3 candies, 2 coffees, and 4 candy bars result I get is 4 candy, 4 candy, 4 candy).
Hope anyone can help i tried to search similar problems but didn't find it though...
for (let bill of dataOfBillHeader.billBodies) {
console.log(dataOfBillHeader)
console.log(this.productToShowOnView)
this.productToShowOnView.cipher = bill.product.cipher;
this.productToShowOnView.name = bill.product.name;
this.productToShowOnView.measure = bill.product.measure;
this.productToShowOnView.count = bill.product.count;
this.productToShowOnView.price = bill.product.price;
this.productToShowOnView.id = dataOfBillHeader.id;
this.productToShowOnView.count = bill.count;
this.productToShowOnView.quantity = bill.quantity;
this.productToShowOnView.discount = bill.discount;
this.productToShowOnView.discountAmount = bill.discountAmount;
this.productToShowOnView.totalPrice = bill.totalPrice;
console.log("to show on view is " + JSON.stringify(this.productToShowOnView));
const newBasket = this.productsInBasket;
this.productsInBasket.push(this.productToShowOnView);
this.productsInBasket = [...newBasket];
this.cd.detectChanges();
}
Well, you are just pushing the same object (reference) in there over and over, namely this.productToShowOnView. Why are you using this.productToShowOnView? Why not a local constant. And with a little magic you can make it a bit smaller, although I don't understand why you would go from one product data format to another one...:
const newBasket = [...this.productsInBasket];
for (let bill of dataOfBillHeader.billBodies) {
const product = {
// no need to get all those individually
...bill.product,
...bill,
//this is weird, all products have the same id?
id: dataOfBillHeader.id,
};
newBasket.push(product);
}
this.productsInBasket = newBasket;
this.cd.detectChanges();

How to update sequentially in order in different rows and insert a new one?

I don't really know how to approach this, thing is, I'm developing a web application and in a section I need to assign projects to other developers, every assignment/project will have a priority of how important it is. Priority 1 is the highest (more important), and priority 5 is lowest (less important).
What the system has to do is, when I add a new priority 1 (or any other priority), if there are other priorities and a priority 1, move the others down (P1 = P2, P2 = P3, P3 = P4) and add the new one as P1.
I made a little piece of code (making everything manually that will only work once but is just for you to see what I want)
//PHP CODE
//prioridad = "P1" from a button
$prioridad = validacion::limpiar_cadena($_POST['prioridad']);
$estado = "";
$pes = array();
//I get all the priorities from my user and save them in this array
//Saving an array of the user's priorities
while ($row = $resultado->fetch_assoc()){
$pes[] = $row["prioridad"];
}
//Replace current priorities with their new one (just once)
if (in_array($prioridad, $pes)){
if (in_array("P5", $pes)){
$estado = "lleno";
}
//Make priority 4 = priority 5 and same for all
//This user just had the first 3 priorities,so this one did nothing but the others updated succesfully just for this example
if (in_array("P4", $pes)){
$upd= $conexion->prepare("UPDATE asignarproyectousuario SET prioridad = 'P5' WHERE idUsuario = 1 AND idProyecto = 32");
$upd->execute();
}
if (in_array("P3", $pes)){
$upd= $conexion->prepare("UPDATE asignarproyectousuario SET prioridad = 'P4' WHERE idUsuario = 1 AND idProyecto = 2");
$upd->execute();
}
if (in_array("P2", $pes)){
$upd = $conexion->prepare("UPDATE asignarproyectousuario SET prioridad = 'P3' WHERE idUsuario = 1 AND idProyecto = 1");
$upd->execute();
}
if (in_array("P1", $pes)){
$upd= $conexion->prepare("UPDATE asignarproyectousuario SET prioridad = 'P2' WHERE idUsuario = 1 AND idProyecto = 3");
$upd->execute();
}
$insert = $conexion->prepare("INSERT asignarproyectousuario(idProyecto, idUsuario, prioridad) VALUES(4, 1, ?)");
$insert->bind_param("s", $prioridad);
$insert->execute();
}
I tried using arrays and adding a value of one to the current priority but I don't know how to make it work, separate the array and assign every value to a row in the database.
I also found queues that make exactly that "movement" of adding one priority and move the others in order, but I haven't found much documentation about it.
This is the example I saw:
$queue = new SplQueue();
$queue->enqueue('prioridad1');
$queue->enqueue('Prioridad2');
$queue->enqueue('Prioridad3');
$queue->unshift('prioridad1');
$queue->rewind(); // always rewind the queue/stack, so PHP can start from the beginning.
while($queue->valid()){
echo $queue->current()."\n"; // Show the first one
$queue->next(); // move the cursor to the next element
}
echo "\n"."\n"."\n";
var_dump($queue);
If you could give me an idea of how to do it or a different example would be very helpful.
Thanks in advance and if my english is not good enough I can try to explain it better.
technique is simple >
you need to know how JSON works
add an Extra column (text) in mysql Table >
store JSON array in that column Like >
[{"TaskName":"XYX","AssignDate":"AnyDate","Priority":"High","PriorityCount":"50"}]
add extra array in JSON / Update array whenever require
itarate the array that finds ("Priority":"High" AND "PriorityCount": "" // highest)
this might help > Getting max value(s) in JSON array

how to script a simple count if

I tried to find this but I could not figure out the answer on the other questions that were posted. I have two conditions that are used to sort data. The months of the year and if it is ranked 1, 2, or 3.
what i need is on a summary page to count how many inputs there are for each month with specific rank
I hope this all makes sense I tried to clarify the best I can, I am really overwhelmed with this and have no type of coding/scripting experience.
Thanks for any help!
I have used the codes below to return the dates and ranks of the data and to extract the month.
It then uses those months in if statements to put on a summary page. What I do not know how to do is from here put a count formula in it. Like with this code here I want it to be similar to the formula if=month=1 and tiers(ranks)= 1 then count (it cant add because if it adds, when the page updates it will add to numbers that it already counted)
for(var i =8;i<=j;i++) { //loops through a data table to see dates and ranks
var dates = oppwon.getRange(i,22).getValue();
var tiers = oppwon.getRange(i,14).getValue();
var month = new Date(dates).getMonth()+1;
switch (true){
case((month==1)): //if it is january
if(tiers==1) // if it is rank 1
jan1.setValue();
if(tiers==2)
jan2.setValue();
Instead of setValue in the loop, you should consider doing the counting within variable/s and only setValue once the loop is completed.
Some suggested code per below:
for(var i =8;i<=j;i++) { //loops through a data table to see dates and ranks
var dates = oppwon.getRange(i,22).getValue();
var tiers = oppwon.getRange(i,14).getValue();
var month = new Date(dates).getMonth()+1;
var countTiers = {}; //count by tiers of months
countTiers[`m${month}`][`t${tiers}`]++;
You will end up getting an object like e.g. {m1: {t1: 2, t2: 1}} after the loop.
Then you can setValue in the desired column for the final count.
You could define a function
function countTiersByMonth ( dataTable, firstline, lastline ) {
var result = [ [0,0,0],[0,0,0],[0,0,0], [0,0,0],[0,0,0],[0,0,0], [0,0,0],[0,0,0],[0,0,0], [0,0,0],[0,0,0],[0,0,0] ];
var dates;
var tiers;
var month;
for(i = firstline; i<=lastline; i++) {
dates = dataTable.getRange(i,22).getValue();
tiers = dataTable.getRange(i,14).getValue();
month = new Date(dates).getMonth();
switch (tiers){ // we filter by tiers because it seems that you only care about
// tiers 1, 2, 3 wheras you care about all the months
case 1:
case 2:
case 3:
result[month][tiers-1]++; //+1 for the respective tier
// of the respective month
break; //other tiers are ignored
};
};
return result;
};
This takes the data table, the first significant line (8 in your example) and the last relevant line ("j" in your example) and outputs an array with 12 elements, one for each month, that contain 3 elements each, one for each tier you wanted to count.
If you want, lets say the results for May, you call
tierlist = countTiersByMonth(oppwon, 8, j) // We do the counting here
print(tierlist[4][0]) // arrays start at 0, so May -> [4], Tier 1 -> [0]
print(tierlist[4][1]) // May, Tier 2
print(tierlist[4][2]) // May, Tier 3

Javascript average within multidimension array

I have a 2D array, sorted by names of students and their various 100m sprint sessions. A snippet of the data array may look like this...
Names Time(s)
ANDREWMICHEALSMITH 13.95
JOHNJAMESPETERSON 13.70
JOHNJAMESPETERSON 13.80
JOHNJAMESPETERSON 12.50
PETERMICHEALHEWITT 12.80
PETERMICHEALHEWITT 12.60
VICENTJAMESSMITH 13.10
VICENTJAMESSMITH 13.50
VICENTJAMESSMITH 13.80
VICENTJAMESSMITH 13.00
I'm desperately needing to convert the table to show student name, their average time and the number of timed sessions, the desirable result as per below...
Names Avg Time(s) Sessions
ANDREWMICHEALSMITH 13.95 1
JOHNJAMESPETERSON 13.33 3
PETERMICHEALHEWITT 12.70 2
VICENTJAMESSMITH 13.35 4
I have drafted a JavaScript code so far unfortunately fails at the very first if statement.
Cannot read property "0" from undefined.
The code also doesn't capture student with nth number of sessions, and no provision for number of sessions yet. Quite frankly my Java knowledge is so limited for the task at hand. I'm in desperate need of some help to get to the end result.
I'm truely grateful for any guidance.
StudentList.sort();
for (var i=0; i<StudentList.length; i++){
if(StudentList[i][0] == StudentList[i+1][0]){
if(StudentList[i+1][0] == StudentList[i+2][0]){
if(StudentList[i+2][0] == StudentList[i+3][0]){
if(StudentList[i+3][0] == StudentList[i+4][0]){
StudentList[i][1] = (StudentList[i][1]+StudentList[i+1][1]+StudentList[i+2][1]+StudentList[i+3][1]+StudentList[i+4][1])/5;
StudentList.splice(i+1,3);
}else{
StudentList[i][1] = (StudentList[i][1]+StudentList[i+1][1]+StudentList[i+2][1]+StudentList[i+3][1])/4;
}
}else{
StudentList[i][1] = (StudentList[i][1]+StudentList[i+1][1]+StudentList[i+2][1])/3;
}
}else{
StudentList[i][1] = (StudentList[i][1]+StudentList[i+1][1])/2;
}
}
}
You could use an object as hash table for names and us ean array as result set for counting and storing the data.
var studentList = [['ANDREWMICHEALSMITH', 13.95], ['VICENTJAMESSMITH', 13.00], ['PETERMICHEALHEWITT', 12.80], ['PETERMICHEALHEWITT', 12.60], ['VICENTJAMESSMITH', 13.10], ['JOHNJAMESPETERSON', 13.70], ['JOHNJAMESPETERSON', 12.50], ['VICENTJAMESSMITH', 13.50], ['JOHNJAMESPETERSON', 13.80], ['VICENTJAMESSMITH', 13.80]],
hash = Object.create(null),
result = [],
array;
studentList.forEach(function (a) {
if (!hash[a[0]]) {
hash[a[0]] = { name: a[0], sum: 0, count: 0, avg: 0 };
result.push(hash[a[0]]);
}
hash[a[0]].sum += a[1];
hash[a[0]].count++;
hash[a[0]].avg = (hash[a[0]].sum / hash[a[0]].count).toFixed(2);
});
array = result.map(function (a) {
return [a.name, a.avg, a.count];
});
console.log(array);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories

Resources