Transform CSV into an Array of Objects - javascript

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>

Related

Move Specific Rows depending on Filtering Keywords within unknown amount of rows using Google Sheets Apps Scripts

I do SEO, and therefore I have a lot of keywords flowing around in different spreadsheets. I'd like a way to filter these into seperate sheets based on specific filters, but I can't for the life of me, figure out how to do this in Google Apps Script.
Criteria I set myself for this to work out:
A list of strings and their corresponding volumes are entered in column 1+2.
A list of filter-words are written in column 3.
The script has to create a new sheet for each of the filter words and move the strings + volumes into these different sheets if the string contains a filter word.
Example:
Filter words: Apple, Banana, Pineapple
String: "The Apple Was Big", Volume: "100"
The script would move the string and volume into the sheet called "Apple" on row 1
(Beware, I'm in no means experienced in coding)
I believe you can use the following structure:
for(let i = 0; i <= column3RowAmount; i++){ //Run as long as there are more filter words
create(column3Row[i]); //create a new sheet with the name of the filter word
for(let j = 0; j <= column1RowAmount; j++){ //Run as long as there are more keywords
if(column1Row[j].indexOf(column3Row[i]) >= 0){ //If the Row in column 1 contains the filter word
column1Row[j].moveToSheet(column3Row[i]); // Make sure not to move Column 3, but only 1+2
}
}
}
Example sheet: https://docs.google.com/spreadsheets/d/15YIMyGmmfZdy094gwuJNxFmTd8h7NOLnA8KevZrGtdU/edit?usp=sharing
Explanation:
Your goal is to create a sheet for every filter-word in column C. Then copy the data in columns A, B but only the rows that include the filter-word to the corresponding sheet.
For starters, you need to get the filter-word list. You can get the full range of column C and filter out the empty cells:
const sh_names = sh.getRange('C1:C').getValues().flat().filter(r=>r!='');
Similarly, you need to get the data in columns A and B:
const data = sh.getRange('A1:B'+sh.getLastRow()).getValues();
The next step is to iterate over sh_names and for every element / filter-word, check if a sheet with that name exists. If it does not exist, then create a sheet with that name, if it exists then skip the creation part:
if(!ss.getSheetByName(s)){
ss.insertSheet().setName(s);}
The next step is to filter data on the rows that include the filter-word:
let f_data = data.filter(r=>r[0].includes(s));
Finally, check if the length of the data is bigger than 0, otherwise there is not data to use and set the values of data to the corresponding sheet:
sheet.getRange(sheet.getLastRow()+1,1,f_data.length,f_data[0].length).setValues(f_data)
Solution
function myFunction() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Ark1');
const filter_sh = ss.getSheetByName('Filter');
const data = sh.getRange('A1:B'+sh.getLastRow()).getValues();
const sh_names = filter_sh.getRange('A1:A'+filter_sh.getLastRow()).getValues().flat();
sh_names.forEach(s=>{
if(!ss.getSheetByName(s)){
ss.insertSheet().setName(s);}
let sheet = ss.getSheetByName(s);
let f_data = data.filter(r=>r[0].includes(s));
if(f_data.length>0){
sheet.getRange(sheet.getLastRow()+1,1,f_data.length,f_data[0].length).setValues(f_data);}
});
}
This function will place all of your results into column 4 next to the appropriate word rather than creating a page for each word. So it runs much faster.
function stringswords() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet1');
const sr=2;
const rgd=sh.getRange(sr,1,sh.getLastRow()-sr+1,2);
const data=rgd.getDisplayValues();
const rgw=sh.getRange(sr,3,sh.getLastRow()-sr+1,1);
const words=rgw.getDisplayValues().flat();
const wiObj={};
words.forEach(function(w,i){wiObj[w]=i});
const rgr=sh.getRange(sr,4,sh.getLastRow()-sr+1,1);
rgr.clearContent();
var results=rgr.getValues();
words.forEach(function(w,i,A){
data.forEach(function(r,j,D) {
if(data[j][0] && data[j][0].indexOf(w)!=-1) {
results[wiObj[w]][0]+=Utilities.formatString('String:%s Vol:%s\n',data[j][0],data[j][1]);
}
});
});
rgr.setValues(results);
}
Image of Data and output:

How do I Filter array from two columns to non-null pairs?

With the code below, I have a Google Sheet, and I'm trying to create arrays from different sections.
function onFormSubmitTest(e) {
//Open spreadsheet based on URL
var ss = SpreadsheetApp.openByUrl('sheetnamehere');
//Set as Active
SpreadsheetApp.setActiveSpreadsheet(ss);
//Set Tabs as Variables
var Rsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Emailer");
var Lsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Unique Databases");
//----Set last Rows as Variables----
// Gets Values from different sections
var formResponses = Rsheet.getRange("N3:N").getValues();
var databaseNames = Lsheet.getRange("A2:B").getValues();
var developerNames = Lsheet.getRange("F2:F").getValues();
// Filters to ranges that have values, ignores null
var lastRvalues = formResponses.filter(String);
var lastLvalues = databaseNames.filter(String);
var lastDvalues = developerNames.filter(String);
// Sorts arrays for faster indexing
var lastR = lastRvalues.sort();
var lastL = lastLvalues.sort();
var lastD = lastDvalues.sort();
// Unique Databases
var currentDatabases = lastL;
// Current Developers
var currentDevelopers = lastD
On the Unique Databases tab, I have 100 rows on the sheet, with only 28 of them having data. If I have the code below, I can see it only has 28 values as expected:
var databaseNames = Lsheet.getRange("A2:A").getValues();
However, when I add the other column, I get 100 values, with the vast majority being ["", ""]. Should note that the 28 values are key>value pair, so if there's a value in A:A, there will be one in B:B. If null in A:A, then B:B is null.
What am I doing wrong?
Indeed, [["", ""], ["", ""]].filter(String) returns the entire array. To see why, replace filter by map:
[["", ""], ["", ""]].map(String) // [",", ","]
Those are truthy strings, with a comma.
A correct way to filter text by nonemptiness of the first column of the range would be
range.getValues().filter(function(row) {return row[0]})
(The usual caveat about 0 value being falsy applies, but it doesn't look like you would encounter numeric 0 there, the column being text. And the string "0" is truthy.)
(Also, "null" is not the right term here, Apps Script returns empty strings "" for empty cells, which is different from null)

Incorrect Range Height - Google Apps Scripts

I am currently trying to get grab values from another spreadsheet and then paste it into a destination spreadsheet. The problem I am running into is that I am getting incorrect range height and incorrect range widths when I run this code. I read something about 2d arrays but I believe I already have a 2d array here to paste to the spreadsheet. Thank you for your time.
function GmailToDrive_StaticTest(gmailSubject, importFileID){
var threads = GmailApp.search('subject:' + gmailSubject + ' -label:uploaded has:attachment'); // performs Gmail query for email threads
for (var i in threads){
var messages = threads[i].getMessages(); // finds all messages of threads returned by the query
for (var j in messages){
var attachments = messages[j].getAttachments(); // finds all attachments of found messages
var timestamp = messages[j].getDate(); // receives timestamp of each found message
var timestampMinusOne = new Date(timestamp.getTime() - (86400000)); // sets the received timestamp to exactly one day prior (# in milliseconds)
var date = Utilities.formatDate(timestampMinusOne, "MST", "yyyy-MM-dd"); // cleans the timestamp string
for (var k in attachments){
var blobs = {
dataType: attachments[k].getContentType(), // retrives the file types of the attachments
data: attachments[k].copyBlob(), // creates blob files for every attachment
fileName: attachments[k].getName()
};
var tempFile = DriveApp.createFile(blobs.data.setContentType('text/csv')).setName(blobs.fileName.split("-", 1).toString() + date); // creates csv files in drive's root per blob file
var tempFileConverted = Drive.Files.copy( {}, tempFile.getId(), {convert: true} ); // converts created files to gsheets
var importData = {
file: tempFileConverted,
ID: tempFileConverted.getId(),
Sheet1: SpreadsheetApp.openById(tempFileConverted.getId() ).getActiveSheet(),
Sheet1_Values: SpreadsheetApp.openById(tempFileConverted.getId() ).getActiveSheet().getDataRange().getValues()
};
tempFile.setTrashed(true);
var importData_Sheet1_Rows = importData.Sheet1.getMaxRows(); - 2;
var importData_Sheet1_Columns = importData.Sheet1.getMaxColumns(); - 2;
var destSheet = SpreadsheetApp.openById(importFileID).getSheets()[0];
destSheet.clearContents();
Logger.log(importData.Sheet1_Values)
destSheet.getRange(1, 1, importData_Sheet1_Rows, importData_Sheet1_Columns).setValues(importData.Sheet1_Values);
DriveApp.getFileById(importData.ID).setTrashed(true);
}
}
}
}
getMaxRows() and getMaxColumns() return the maximum number of column and rows in a sheet, while getDataRange().getValues() return all the values in a sheet that contain data .
So, unless all the cells in a sheet have data the dimensions won't match !
The best you could do is to get the actual size of the data array and use that to set the range for the values in the destination sheet.
It goes (more) simply like this :
destSheet.getRange(1, 1, importData.Sheet1_Values.length, importData.Sheet1_Values[0].length).setValues(importData.Sheet1_Values);
you don't need the other values for rows and columns, just ignore that in your script.

Read CSV file based on columns

I am working in an Angular js project where I have to read the CSV file column wise using javascript. I have retrieved the CSV and printed it in the console. I am able to split the csv row wise. How to do it based on columns?
Thanks in advance.
CSV is nothing but a 2 dim array. By using 2 for loop you can do.
for example:
for(var i=0;i<col.length;i++){
for(var j=0;j<rows.length;j++){
arr[i][j]
}
}
Interestingly, it sounds easy to parse CSV files but it can get complicated quickly (depending on where your CSV comes from: user-generated, fixed in format from an API, ...):
Parsing headers
Different number of headers and data columns
Delimiter (Germans often use ; instead of ,)
Number format (Germans often use the , instead of . as decimal separators)
Quoted data (maybe with a delimiter inside the quote data)
Whitespace
Line endings
...
That's why there are a lot of CSV parsers available on npm (https://www.npmjs.com/search?q=csv). Some are focused on parsing speed (e.g. https://www.npmjs.com/package/fast-csv) some on convenience (e.g. https://www.npmjs.com/package/papaparse).
But all have in common (as far as I know) that they return row wise. Which is often caused to be able to process streams which will pass the data line wise and not column wise.
Here's a code example to get your data column wise:
const input = `header_1,header_2
value 1,value 2
value 3,value 4`
// get rows -> here \n as line ending is known
const rows = input.split('\n');
// get the first row as header
const header = rows.shift();
// get number of columns by splitting the header
// , as delimiter is known here. Could be different ...
const numberOfColumns = header.split(',').length
// initialize 2D-array with a fixed size
const columnData = [...Array(numberOfColumns)].map(item => new Array());
for(var i=0; i<rows.length; i++) {
var row = rows[i];
var rowData = row.split(',');
// assuming that there's always the same
// number of columns in data rows as in header row
for(var j=0; j<numberOfColumns; j++) {
columnData[j].push(rowData[j]);
}
}
console.log("columnData = " + JSON.stringify(columnData, null, 4));
Output will be:
columnData = [
[
"value 1",
"value 3"
],
[
"value 2",
"value 4"
]
]
Not included is stripping whitespace, converting numbers, ...
For convinience you could use papaparse to get the data row wise and use the nested for loop again:
const Papa = require('papaparse');
// example data with delimiter ; and empty lines
const input = `header_1;header_2
1;"2"
3;4`;
// options for papaparse
const parseOptions = {
quoteChar: '"', // quoting character
delimiter: ';',
skipEmptyLines: true, // ignore empty lines
dynamicTyping: true, // parse numbers automatically
}
const parseResult = Papa.parse(input, parseOptions);
const parsedData = parseResult.data;
// get the first row as header
const header = parsedData.shift();
const numberOfColumns = header.length;
// initialize 2D-array with a fixed size
const columnData = [...Array(numberOfColumns)].map(item => new Array());
for(var i=0; i<parsedData.length; i++) {
var rowData = parsedData[i];
for(var j=0; j<numberOfColumns; j++) {
columnData[j].push(rowData[j]);
}
}
console.log("columnData = " + JSON.stringify(columnData, null, 4));
Output will be:
columnData = [
[
1,
3
],
[
2,
4
]
]

Generating a price per item in an html table using a 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.

Categories

Resources