how to script a simple count if - javascript

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

Related

Google Apps Script - Compare two sheets for changes by column names instead of hardcoded ranges

I have two sheets, "IMPORT" and "CASES".
In the "IMPORT" sheet, I am importing data from an external source that sometimes have more columns or existing columns are arranged each time differently.
In the "CASES" sheet, this is where I store a weekly snapshot of all last week's imported data, and I add my additional columns with more pieces of information such as comments, next steps etc.
I am looking for a way to compare both sheets without hardcoding any column ranges. I thought the most efficient way to do it is by looking up column header names in both sheets and then checking for changes in reference to the "Case Number" row. Please let me know if you can think of a better way.
I have already managed to write a code to look through headers and identify the Index number for a specific column name, "Case Number".
This column will always be present in both sheets, and it could serve as a reference point to the row that should be validated, but it could be a different row for each sheet at a time.
I will need the same time loop through all the column headers from the CASES sheet and check for updates from the IMPORT sheet.
I only need to check/loop for changes for few specific columns from the CASES sheet. Columns names such: Contact Name, Title, Priority, Status.
I am aiming to achieve 3 possible outcomes:
[ COMPLETED ] "Case Number" from the CASES sheet was NOT FOUND in the IMPORT sheet - that means the case was closed since last week.
Action: Highlight an entire row in the CASES sheet as grey (this will indicate the case is no longer open and should be removed from the list after confirmation).
"Case Number" from the IMPORT sheet was NOT FOUND in the CASES sheet - this means the case is new and needs to be added to the CASES sheet at the bottom.
Action: Copy the data from the IMPORT sheet to the CASES sheet and paste it in the correct columns at the bottom and highlight the entire row as green to indicate a new data entry.
For all non-existing columns in the CASES sheet that are in the IMPORT sheet, those should be skipped.
"Case Number" from the IMPORT sheet WAS FOUND in the CASES sheet - for the matching Case Number records, I need to validate if there were any changes in any CASES sheet columns since last week.
Action: If a change was found in any of the cells, update the cell with new data in CASES sheet and change the cell background colour to yellow to highlight the cell was updated. For cells without changes, skip.
I apologise for the lengthy problem statement.
I am new to JS and GAS, and I wrote it hoping that some JavaScript expert will understand my idea and advise maybe the easier way to complete my project.
Currently, I am stuck with finding a proper way to loop through Header Names then check cell value from the IMPORT sheet and comparing it with the CASES sheet based on the Case Name value/row.
OUTCOME 1 - Completed
OUTCOME 2 - In Progress
OUTCOME 3 - tbd...
I will continue to update this topic to show the latest progress on this project.
All the examples I found so far on the Internet were based on hardcoded ranges of cells and columns. I think my approach is interesting as it gives future-proof flexibility to the datasets.
Please let me know your thoughts or ideas for a more straightforward approach :)
Link to live sheet
UPDATED code:
// Create Top Menu
function onOpen() {
let ui = SpreadsheetApp.getUi();
ui.createMenu('>> REPORTS <<').
addItem('Highlight Closed Cases', 'closedCases').
addItem('Check for new Cases', 'addCases').addToUi();
}
// IN PROGRESS (Outcome 2) - Add and highlight new cases in CASES sheet
function addCases() {
let ss = SpreadsheetApp.getActiveSpreadsheet();
// Get column index number for Case Number
let activeImportCol = getColumnIndex("Case Number", "IMPORT");
let activeCasesCol = getColumnIndex("Case Number", "CASES");
let importHeaders = loadHeaderNames("IMPORT");
let casesHeaders = loadHeaderNames("CASES");
// Load Case Number columns values into array
let loadImportValues = getColumnValues("Case Number", "IMPORT");
let loadCasesValues = getColumnValues("Case Number", "CASES");
// Convert to 1D array
let newImportValues = loadImportValues.map(function (row) { return row[0]; });
let newCasesValues = loadCasesValues.map(function (row) { return row[0]; });
// Get number of columns
var numImportCol = ss.getSheetByName("IMPORT").getLastColumn();
// Loop through IMPORT sheet "Case Number" column to find new Case Numbers - execute OUTCOME 3 or 2
for (var line in newImportValues) {
var isMatched = newCasesValues.indexOf(newImportValues[line]);
if (isMatched !== -1) {
// "Case Number" from the IMPORT sheet WAS FOUND in the CASES sheet - EXECUTE OUTCOME 3
// ****************************************************************************************
// For the matching Case Number records, I need to validate if there were any changes in any CASES sheet columns since last week
// Action: If a change was found in any of the cells, update the cell with new data in CASES sheet
// and change the cell background colour to yellow to highlight the cell was updated. For cells without changes, skip.
} else {
// "Case Number" from the IMPORT sheet was NOT FOUND in the CASES sheet - EXECUTE OUTCOME 2
// ****************************************************************************************
// Copy the new data row from the IMPORT sheet to the CASES sheet and paste it in the correct columns
// at the bottom and highlight the entire row as green to indicate a new data entry.
// For all non-existing/not matching column names in the CASES sheet that are not in IMPORT sheet, those should be skipped.
}
}
}
// COMPLETED (Outcome 1) - Highlight entire row grey for missing values in CASES sheet
function closedCases() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Load all Casen Number columns values into array
var importValues = getColumnValues("Case Number", "IMPORT");
var casesValues = getColumnValues("Case Number", "CASES");
// Convert to 1D array
var newImportValues = importValues.map(function (row) { return row[0]; });
var newCasesValues = casesValues.map(function (row) { return row[0]; });
// Get column index number for Case Number
var activeCol = getColumnIndex("Case Number", "CASES");
// Get number of columns
var numCol = ss.getSheetByName("CASES").getLastColumn();
// Loop though CASES "Case Number" column and highlight closed cases (not found in IMPORT tab)
for (var line in newCasesValues) {
var isMatched = newImportValues.indexOf(newCasesValues[line]);
if (isMatched !== -1) {
// If found then...
ss.getSheetByName("CASES").getRange(+line + 2, 1, 1, numCol).setBackground(null);
} else {
// Higlight row with missing cases - grey
ss.getSheetByName("CASES").getRange(+line + 2, 1, 1, numCol).setBackground("#d9d9d9");
};
}
}
// Load column values
function getColumnValues(label, sheetName) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
// Get column number for Case Number
var colIndex = getColumnIndex(label, sheetName);
// Get number of rows in Case Number
var numRows = ss.getLastRow() - 1;
// Load Case Number values into array
var colValues = ss.getRange(2, colIndex, numRows, 1).getValues();
return colValues;
}
// Load column header names
function loadHeaderNames(sheetName) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
let HeaderArray = ss.getRange(1, 1, 1, ss.getLastColumn()).getValues()[0];
let colidx = {};
HeaderArray.forEach((h, i) => colidx[h] = i);
return HeaderArray;
}
// Get column name index value
function getColumnIndex(label, sheetName) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
// Find last column
var lc = ss.getLastColumn();
// Load headers into array
var lookupRangeValues = ss.getRange(1, 1, 1, lc).getValues()[0];
// Search for label and return the column number
var index = lookupRangeValues.indexOf(label) + 1;
return index;
}
One way to make all this processing much easier is to reorder the columns so that they always fall in the same place, like this:
=arrayformula(
iferror(
vlookup(
hlookup("Case Number"; IMPORT!A1:G; row(IMPORT!A2:G); false);
{
hlookup("Case Number"; IMPORT!A1:G; row(IMPORT!A1:G); false) \
IMPORT!A1:G
};
match(IMPORT!A1:G1; CASES!A1:G1; 0) + 1;
false
)
)
)
The formula will reorder the columns in IMPORT so that the columns are in the same order as they are listed in CASES!A1:G1.
You can then use further formulas or script functions to work on the data, confident that a particular kind of data will always be in the same column. For instance, you can list closed cases with something like this:
=filter( 'CASES normalized'!A2:G; isna(match('CASES normalized'!C2:C; 'IMPORT normalized'!C2:C; 0)) )
...and open cases like this:
=filter( 'CASES normalized'!A2:G; match('CASES normalized'!C2:C; 'IMPORT normalized'!C2:C; 0) )
See your sample spreadsheet.

Sort Nested Json Object based on value in for loop?

Hoping someone can help me out here or at least point me in the right direction. I have spent hours trying to get this sorted and I am lost.
The code below is just mock, my actual json is returned via AJAX using jquery. My problem is not sorting, but sorting on a nested json object.
I am trying to sort the json output based on cost. (lowest cost to highest), my attempts have failed and I cannot get this sorted. I keep getting "sort" is undefined.
Any help would be appreciated or if you can just point out what I am doing wrong here.
var json = '{"shipping_method":{"ups":{"title":"United Parcel Service","quote":{"12":{"code":"ups.12","title":"UPS 3 Day Select","cost":117.3,"tax_class_id":"0","text":"$117.30"},"13":{"code":"ups.13","title":"UPS Next Day Air Saver","cost":242.52,"tax_class_id":"0","text":"$242.52"},"14":{"code":"ups.14","title":"UPS Next Day Air Early A.M.","cost":279.95,"tax_class_id":"0","text":"$279.95"},"03":{"code":"ups.03","title":"UPS Ground","cost":54.62,"tax_class_id":"0","text":"$54.62"},"02":{"code":"ups.02","title":"UPS 2nd Day Air","cost":177.31,"tax_class_id":"0","text":"$177.31"},"01":{"code":"ups.01","title":"UPS Next Day Air","cost":248.08,"tax_class_id":"0","text":"$248.08"}},"sort_order":"","error":""}}}';
/*
This doesnt work and returns undefined.
json["shipping_method"]["quote"].sort(function(a, b) {
return a['cost'] > b['cost'];
});
// I found this example, but also didn't work.
custSort = (prop1, prop2 = null, direction = 'asc') => (e1, e2) => {
const a = prop2 ? e1[prop1][prop2] : e1[prop1],
b = prop2 ? e2[prop1][prop2] : e2[prop1],
sortOrder = direction === "asc" ? 1 : -1
return (a < b) ? -sortOrder : (a > b) ? //sortOrder : 0;
};
json.sort(custSort("quote", "cost", "desc"));*/
json = JSON.parse(json);
for (var i in json["shipping_method"]) {
// EDIT:: I want the sorting to occur here if possible.
for (j in json["shipping_method"][i]["quote"]) {
//EDIT:: I want to keep this for loop, but with the results sorted by cost
console.log(json["shipping_method"][i]["quote"][j]["cost"]);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Convert Object to Sorted Array
The object can be flattened out so that parent keys are included in the deep object as it's been iterated over. An early example to that can be found in this answers edit history. It has been removed since information like the quote-id was not deemed important.
Below is an example of using Object.values, which traverses an object and only returns an array of that objects values (discarding the keys). The values can then be sorted as intended, by cost.
const json = JSON.parse(getData());
for (let method in json["shipping_method"]) {
// cache
let quotes = json['shipping_method'][method]['quote']
// convert object to array and sort
let sortedQuotes = Object.values(quotes).sort((a, b)=>a.cost-b.cost);
console.log(sortedQuotes)
}
/* Dummy Data */
function getData() {
return '{"shipping_method":{"ups":{"title":"United Parcel Service","quote":{"12":{"code":"ups.12","title":"UPS 3 Day Select","cost":117.3,"tax_class_id":"0","text":"$117.30"},"13":{"code":"ups.13","title":"UPS Next Day Air Saver","cost":242.52,"tax_class_id":"0","text":"$242.52"},"14":{"code":"ups.14","title":"UPS Next Day Air Early A.M.","cost":279.95,"tax_class_id":"0","text":"$279.95"},"03":{"code":"ups.03","title":"UPS Ground","cost":54.62,"tax_class_id":"0","text":"$54.62"},"02":{"code":"ups.02","title":"UPS 2nd Day Air","cost":177.31,"tax_class_id":"0","text":"$177.31"},"01":{"code":"ups.01","title":"UPS Next Day Air","cost":248.08,"tax_class_id":"0","text":"$248.08"}},"sort_order":"","error":""}}}';
}
.as-console-wrapper {
max-height: 100vh !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Quotes by Cost per Shipping Method
This assumes that the quote ID is needed (perhaps to be placed on a row); otherwise this can be simplified using Object.values in place of Object.entries (amongst other changes).
Disregard what the output function is doing. It is a quick example, that doesn't ensure proper cell order and has a host of other limitations and vulnerabilities. It is only used to demonstrate that the original quote data is still available after sorting.
const data = JSON.parse(getData());
for (let method in data.shipping_method) {
output({row: method}, {class:'capitalize'})
// cache
let quotes = data.shipping_method[method].quote
let sortContent = Object.entries(quotes);
let sortedQuotes = sortContent.sort((a,b)=>a[1].cost-b[1].cost).map(i=>i[0]);
for (let quoteId of sortedQuotes){
let quoteInfo = quotes[quoteId];
output({cell: quoteInfo})
}
}
/* Dummy Data */
function getData() {
return '{"shipping_method":{"ups":{"title":"United Parcel Service","quote":{"12":{"code":"ups.12","title":"UPS 3 Day Select","cost":117.3,"tax_class_id":"0","text":"$117.30"},"13":{"code":"ups.13","title":"UPS Next Day Air Saver","cost":242.52,"tax_class_id":"0","text":"$242.52"},"14":{"code":"ups.14","title":"UPS Next Day Air Early A.M.","cost":279.95,"tax_class_id":"0","text":"$279.95"},"03":{"code":"ups.03","title":"UPS Ground","cost":54.62,"tax_class_id":"0","text":"$54.62"},"02":{"code":"ups.02","title":"UPS 2nd Day Air","cost":177.31,"tax_class_id":"0","text":"$177.31"},"01":{"code":"ups.01","title":"UPS Next Day Air","cost":248.08,"tax_class_id":"0","text":"$248.08"}},"sort_order":"","error":""}}}';
}
/* Really simple output for demo purpose */
function output(data, options={}){
if ('row' in data){
let $col = $('<td></td>', options).html(data.row)
let $row = $('<tr></tr>').append($col);
$('tbody').append( $row )
}
else if ('cell' in data){
let $row = $('<tr></tr>')
for( let key in data.cell ){
let $col = $('<td></td>', options).html(data.cell[key])
$row.append($col)
}
$('tbody').append( $row )
}
}
.capitalize {
text-transform: uppercase;
}
td {
min-width: 5rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead></thead>
<tbody></tbody>
</table>
Your objects can have any amount of properties and you can choose to sort by whatever object property you want, number or string, if you put the objects in an array.
var item = JSON.parse(json).shipping_method.ups.quote;
Use Object.values() to get array of values of the JSON object and then use slice() method to copy the array of JSON objects and not just make a reference.
var byCost = Object.values(item).slice(0);
Finally you can use sort function for that array of objects.
byCost.sort(function(a,b) {return a.cost - b.cost});
var json = '{"shipping_method":{"ups":{"title":"United Parcel Service","quote":{"12":{"code":"ups.12","title":"UPS 3 Day Select","cost":117.3,"tax_class_id":"0","text":"$117.30"},"13":{"code":"ups.13","title":"UPS Next Day Air Saver","cost":242.52,"tax_class_id":"0","text":"$242.52"},"14":{"code":"ups.14","title":"UPS Next Day Air Early A.M.","cost":279.95,"tax_class_id":"0","text":"$279.95"},"03":{"code":"ups.03","title":"UPS Ground","cost":54.62,"tax_class_id":"0","text":"$54.62"},"02":{"code":"ups.02","title":"UPS 2nd Day Air","cost":177.31,"tax_class_id":"0","text":"$177.31"},"01":{"code":"ups.01","title":"UPS Next Day Air","cost":248.08,"tax_class_id":"0","text":"$248.08"}},"sort_order":"","error":""}}}';
var item = JSON.parse(json).shipping_method.ups.quote;
var byCost = Object.values(item).slice(0);
byCost.sort(function(a,b) {return a.cost - b.cost});
console.log(byCost)
It doesn't seem like you are accessing the right path here... Looking at the JSON you posted you should be attempting to sort shipping_method.ups.quote its also worth noting that shipping_method.ups.quote is an object and must be converted to an Array to invoke .sort as this method lives on the Array prototype.
This can be done several ways but Object.values() is one such way.
you may try the following,
json = JSON.parse(json);
let item = json.shipping_method.ups.quote,
temp = [];
for (let key in item) {
temp.push(item[key]);
}
temp.sort((x, y) => x.cost - y.cost);
json.shipping_method.ups.quote = temp;
converting your object into array and then sort;
As i can see , your problem is to sort the object with cost as their keys should stays same ,
try out this ,
var json = '{"shipping_method":{"ups":{"title":"United Parcel Service","quote":{"12":{"code":"ups.12","title":"UPS 3 Day Select","cost":117.3,"tax_class_id":"0","text":"$117.30"},"13":{"code":"ups.13","title":"UPS Next Day Air Saver","cost":242.52,"tax_class_id":"0","text":"$242.52"},"14":{"code":"ups.14","title":"UPS Next Day Air Early A.M.","cost":279.95,"tax_class_id":"0","text":"$279.95"},"03":{"code":"ups.03","title":"UPS Ground","cost":54.62,"tax_class_id":"0","text":"$54.62"},"02":{"code":"ups.02","title":"UPS 2nd Day Air","cost":177.31,"tax_class_id":"0","text":"$177.31"},"01":{"code":"ups.01","title":"UPS Next Day Air","cost":248.08,"tax_class_id":"0","text":"$248.08"}},"sort_order":"","error":""}}}';
var json = JSON.parse(json);
let data = []
for(var i in json.shipping_method.ups.quote){
data.push(json.shipping_method.ups.quote[i])
data.sort((a,b) => a.cost - b.cost);
}
This create those key agains as they are before
let final = {} ;
data.forEach(el => final[el.code.split('.')[1]] = el);
Finally update the qoute with the latest sorted quotes :
json.shipping_method.ups.quote = final;

Pull Gmails into a Google Sheet

This script works brilliantly to pull emails into my sheet. My problem is that the function only pulls the first two fields listed. e.g., getPlainBody, getSubject - even though more fields are asked for. So instead of having one function that pulls all the fields I need (getPlainBody, getSubject, getTo, getDate, getFrom) I only get the first two (getPlainBody, getSubject). Is there an obvious modification that will pull all 5 fields into the sheet?
function getEmails_(q) {
sh0.clear();
var emails = [];
var threads = GmailApp.search(q);
for (var i in threads) {
var msgs = threads[i].getMessages();
for (var j in msgs) {
emails.push([msgs[j].getPlainBody(), [msgs[j].getSubject(), [msgs[j].getDate(), [msgs[j].getTo(), [msgs[j].getFrom()
]]]]]);
}
}
return emails;
}
function appendData_(sh0, array2d) {
sh0.getRange(sh0.getLastRow() + 1, 1, array2d.length, array2d[0].length).setValues(array2d);
}
function saveEmails() {
var array2d = getEmails_(SEARCH_QUERY);
if (array2d) {
appendData_(sh0, array2d);
}}
Your code is fine the problem is how you are constructing the 2D array.
in the .push() method, your use of the square brackets - [] - is building an array within an array within another array within another array within another array within another array, it's easier to see it in the screenshot below.
What you need is 1 array of horizontals cells with an array of vertical rows.
So change:
emails.push([msgs[j].getPlainBody(), [msgs[j].getSubject(), [msgs[j].getDate(), [msgs[j].getTo(), [msgs[j].getFrom()]]]]]);
to
emails.push([msgs[j].getPlainBody(), msgs[j].getSubject(), msgs[j].getDate(), msgs[j].getTo(), msgs[j].getFrom()]);
On a personal note, I usually always format the date to something a little more readable. You can use Utilities to do this. Ex: format: Thu Jun 15 2017 11:18:18 GMT+0700 (ICT) to 15/06/2017 # 11:18
var formatDate = Utilities.formatDate(emails[i][2], 'GMT+07:00', 'dd/MM/yyyy # HH:mm')

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.

Javascript adding array to specific index

When i have the following global variable on my application start :
events = [];
Then if i go fetch something with ajax with the following simplified code snippet :
events[0] = [];
setTimeout(function fetchEventsThisWeek(){
$.ajax({
url: '/event/getEventsBetweenDates',
type: 'POST',
data : { from_date : currentweek.from_date.toString("yyyy-MM-d") , to_date : currentweek.to_date.toString("yyyy-MM-d"), limit : limit, offset : offset },
success: function(data) {
jQuery.each(data, function(index){
events[0].push(data[index]['attributes']);
});
offset = offset + limit;
entry_count = entry_count + data.length;
if(data.length < limit) { // We reached the end of the table so we don't need to call the function again
renderEvents(current, offset - limit, entry_count);
//Make sure the current next week button gets enabled because we are done with the results
} else {
renderEvents(current, offset - limit, offset);
setTimeout(fetchEventsThisWeek, 150); // There are more results, continue
}
}
})
}, 150);
This recursive function just fetches all events between two dates and keeps calling itself until there is no record in the db left.
My problem is:
With the variable:
events[0] = [];
I want to specify the index of the array as my week entry. So if i look for a specific week, i can get all the entries that already have been fetched from my array by the array index.
My problem is, when i want to fetch more weeks, so for example:
events[1] = [];// Index 1 would represent the next week
The array just expands in size and all gets appended to the end, so i have one big array and not a multidimensional one. Why is this? And how can i achieve this behaviour?
Edit:
Let me expand on my question.
I need several arrays of json objects in the events variable.
So..
events[0] = [ /*contains array of json objects */];
events[1] = [ /*contains array of json objects */];
events[2] = [ /*contains array of json objects */];
Each array index represent 1 week. So index 0 is the current week, index 1 is week 1, index 2 is week 2 and so forth. I even want to do the following but i don't know if this is even possible:
events[-1] = [ /*contains array of json objects */];
Where the index -1 would be 1 week in the past. Could anybody let me know if this is possible?
You're looking for Array.unshift:
events.unshift([]);
Documentation

Categories

Resources