How to check multiple arrays at once? - javascript

I have this code. It checks if auctions[0] exists and if it does, it gets the value and sends it and continues to the next number. If not it will move on to the next number and do the same thing. And I need it to check if it exists until it reaches number 30
Are there any alternatives to this that is less bulky and messy?
if (ahValue.auctions[0]){
var itemName = ahValue.auctions[0].item_name
var itemLore = ahValue.auctions[0].item_lore
var itemTier = ahValue.auctions[0].tier
var itemSeller = ahValue.auctions[0].auctioneer
var itemBids = ahValue.auctions[0].bids.length
console.log(`${itemName}${itemLore}${itemTier}${itemSeller}${itemBids}`)
}
if (ahValue.auctions[1]){
var itemName = ahValue.auctions[1].item_name
var itemLore = ahValue.auctions[1].item_lore
var itemTier = ahValue.auctions[1].tier
var itemSeller = ahValue.auctions[1].auctioneer
var itemBids = ahValue.auctions[1].bids.length
console.log(`${itemName}${itemLore}${itemTier}${itemSeller}${itemBids}`)
}
//copy and paste until it reaches 30
if (ahValue.auctions[30]){
var itemName = ahValue.auctions[30].item_name
var itemLore = ahValue.auctions[30].item_lore
var itemTier = ahValue.auctions[30].tier
var itemSeller = ahValue.auctions[30].auctioneer
var itemBids = ahValue.auctions[30].bids.length
console.log(`${itemName}${itemLore}${itemTier}${itemSeller}${itemBids}`)
}

Use a for loop:
for(let i = 0; i <= 30; i++) {
if (ahValue.auctions[i]){
var itemName = ahValue.auctions[i].item_name
var itemLore = ahValue.auctions[i].item_lore
var itemTier = ahValue.auctions[i].tier
var itemSeller = ahValue.auctions[i].auctioneer
var itemBids = ahValue.auctions[i].bids.length
console.log(`${itemName}${itemLore}${itemTier}${itemSeller}${itemBids}`)
}
}

try something like this.
auctions.length this will return the lenght of array, and this will help you to iterate over all the elements.
This is the running code snippet.
var auctions = [];
auctions[0] = { "item_name" : "item_name1", "item_lore" : "item_lore1", "tier" : "tier1", "auctioneer" : "auctioneer1" , "bids":"bids1"};
auctions[1] = { "item_name" : "item_name2", "item_lore" : "item_lore2", "tier" : "tier2", "auctioneer" : "auctioneer2" , "bids":"bids2"};
for(var i = 0; i < auctions.length; i++){
if(auctions[i]){
console.log(auctions[i].item_name);
}
}
And your full code will look like this:
for(let i = 0; i <= ahValue.auctions.length; i++) {
if (ahValue.auctions[i]){
var itemName = ahValue.auctions[i].item_name
var itemLore = ahValue.auctions[i].item_lore
var itemTier = ahValue.auctions[i].tier
var itemSeller = ahValue.auctions[i].auctioneer
var itemBids = ahValue.auctions[i].bids.length
console.log(`${itemName}${itemLore}${itemTier}${itemSeller}${itemBids}`)
}
}

Related

Certain number question being missed in regex

I have the following if statement that removes the first instances of a number followed by the period. However, I am noticing it is missing to catch some of them (ex. "16.", "23.", "24.", etc.) and not sure why.
Here is the function:
function quesCleanUp(ques){
//Checks the first instance of "." and removes it and the number
if(ques.match(/[0-9]\./g)?.length > 1){//(ques.match(/./g)?.length > 1){
var quesClean = ques.replace(/^[^\.]*\./, '').trim();
} else{
var quesClean = ques.trim();
}
return quesClean;
}
The following for loop extracts the question from the google form:
for (var i = 0; i < items.length; i++) {
var item = items[i];
switch(item.getType()) {
case FormApp.ItemType.MULTIPLE_CHOICE:
var question = item.asMultipleChoiceItem();
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "Multiple Choice";
var optns = [];
var answr;
var answers = question.getChoices();
answer_val = false;
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue().trim();
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr = answers[j].getValue().trim();
for(var x = 0; x < optns.length; x++){
if(answr == optns[x]){
answer_val = true;
break;
}
}
}
}
var multiJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON1: " + JSON.stringify(multiJSON));
constructedJSON[i+1] = multiJSON;
break;
case FormApp.ItemType.CHECKBOX:
var question = item.asCheckboxItem();
//var ques = question.getTitle().trim();//.replace(/\s/g, "");
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "CheckBox";
var optns = [];
var answr = [];
var answers = question.getChoices();
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue().trim();//replace(/\s/g, "");
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr.push(answers[j].getValue().trim());
}
}
var checkJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON2: " + JSON.stringify(checkJSON));
constructedJSON[i+1] = checkJSON;
break;
case FormApp.ItemType.PARAGRAPH_TEXT:
var question = item.asParagraphTextItem();
//var ques = question.getTitle().trim();//.replace(/\s/g, "");
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "free response";
var optns = [];
var answr;
var paraJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON3: " + JSON.stringify(paraJSON));
constructedJSON[i+1] = paraJSON;
break;
case FormApp.ItemType.TEXT:
var question = item.asTextItem();
//var ques = question.getTitle().trim();
var question_type = "free response";
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var optns = "";
var answr = "";
var textJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON4: " + JSON.stringify(textJSON));
constructedJSON[i+1] = textJSON;
break;
}
The following example is the type of question 16. What is the meaning of life?
And the expected output: What is the meaning of life?
Try using /[0-9]+./g to catch more than one digit
As a quick fix, in the function quesCleanUp() try to change the line:
if(ques.match(/[0-9]\./g)?.length > 1){//(ques.match(/./g)?.length > 1){
With:
if (ques.match(/^[0-9]+\./g).length > 0) {
I suspect you got the downvotes because you posted the code with glared typos. It looks like you didn't even try to debug it first. And as the icing on the cake you accepted a wrong answer.
And probably the function can be boiled down to just one line:
const quesCleanUp = q => q.replace(/^\d+\./,'').trim();
Here is how it works:
var questions = ['1. aaa', '16. What', '23. That', 'No nums'];
const quesCleanUp = q => q.replace(/^\d+\./,'').trim();
questions.forEach(q => console.log(quesCleanUp(q)));
Expected output:
aaa
What
That
No nums

How to use the result of an IF statement as a variable

I have a code as follows:
function DetailFacture2() {
var ss = SpreadsheetApp.getActive();
var DetailDEVIS = SpreadsheetApp.setActiveSheet(ss.getSheetByName('DetailDEVIS'));
var FACTUREDevis = SpreadsheetApp.setActiveSheet(ss.getSheetByName('FACTUREDevis'));
var DetailFactureDevis = SpreadsheetApp.setActiveSheet(ss.getSheetByName('DetailFactureDevis'));
var lastrowpaste = FACTUREDevis.getLastRow();
var numrow = FACTUREDevis.getRange(lastrowpaste,13).getValue()
var lastrowpaste2 = DetailFactureDevis.getLastRow() - numrow +2;
var data = DetailDEVIS.getDataRange().getValues();
var DetailD = FACTUREDevis.getRange(lastrowpaste,2).getValue();
for(var i = 0; i<data.length;i++){
if(data[i][1] == DetailD){ //[1] because column B
var firstrowcopy = i+1;
Logger.log(firstrowcopy)
return (firstrowcopy)
}
}
};
It does return the correct value, but how do you use "firstrowcopy" as a fixed var?
I would like to use as follows:
function DetailFacture2() {
var ss = SpreadsheetApp.getActive();
var DetailDEVIS = SpreadsheetApp.setActiveSheet(ss.getSheetByName('DetailDEVIS'));
var FACTUREDevis = SpreadsheetApp.setActiveSheet(ss.getSheetByName('FACTUREDevis'));
var DetailFactureDevis = SpreadsheetApp.setActiveSheet(ss.getSheetByName('DetailFactureDevis'));
var lastrowpaste = FACTUREDevis.getLastRow();
var numrow = FACTUREDevis.getRange(lastrowpaste,13).getValue()
var lastrowpaste2 = DetailFactureDevis.getLastRow() - numrow +2;
var data = DetailDEVIS.getDataRange().getValues();
var DetailD = FACTUREDevis.getRange(lastrowpaste,2).getValue();
for(var i = 0; i<data.length;i++){
if(data[i][1] == DetailD){ //[1] because column B
var firstrowcopy = i+1;
var source = DetailDEVIS.getRange(firstrowcopy,1,numrow-1);
var destination = DetailFactureDevis.getRange(lastrowpaste2,3);
source.copyTo(destination);
}
}
};
But, as one would expect, it cannot work as it loops...
Not sure if I understand your question too. The code doesn't look well. Here is just my guess. Try to change the last lines this way:
// ...
var firstrowcopy = 0;
for (var i = 0; i < data.length; i++){
if(data[i][1] == DetailD){ //[1] because column B
firstrowcopy = i+1;
break;
}
}
var source = DetailDEVIS.getRange(firstrowcopy,1,numrow-1);
var destination = DetailFactureDevis.getRange(lastrowpaste2,3);
source.copyTo(destination);
}

Create a Sub sheet from Master Sheet, using import range, filter and match Google App Script

I want to fetch data from a google sheet data dump/master sheet. There is a sheet for each month. Import/match the data to columns that are in a different order in another sub spreadsheet and put all months on one sheet. Lastly, I want to filter the data by person, status and date, so only these items will show unless Cell H1 is populated. If cell H1 is populated and not null, all data that meets the criteria will be shown.
Master: https://docs.google.com/spreadsheets/d/1nIzCqQUL1K4HwYUGV0jxjJjLKSFaeqVn27f_pkoL9j0/edit?usp=sharing
Subsheet:https://docs.google.com/spreadsheets/d/1-V0F_pJTKFmP8jRBwpIzBe_sP7GbC-314oUB97N0K-0/edit#gid=0
function Importmatchfilter() {
// source sheet
var ss = ('1nIzCqQUL1K4HwYUGV0jxjJjLKSFaeqVn27f_pkoL9j0/edit#gid=1395833187');
var ssn1 = ss.getSheetByName('April'); ('A:Z')
var ssn2 = ss.getSheetByName('May'); ('A:Z')
var ssn3 = ss.getSheetByName('June'); ('A:Z')
var ssn4 = ss.getSheetByName('July'); ('A:Z')
var ssn5 = ss.getSheetByName('August'); ('A:Z')
var ssn6 = ss.getSheetByName('September'); ('A:Z')
var ssn7 = ss.getSheetByName('October'); ('A:Z')
var ssn8 = ss.getSheetByName('November'); ('A:Z')
var ssn9 = ss.getSheetByName('December'); ('A:Z')
// Get full range of data
var SRange1 = ssn1.getDataRange();
var SRange2 = ssn2.getDataRange();
var SRange3 = ssn3.getDataRange();
var SRange4 = ssn4.getDataRange();
var SRange5 = ssn5.getDataRange();
var SRange6 = ssn6.getDataRange();
var SRange7 = ssn7.getDataRange();
var SRange8 = ssn8.getDataRange();
var SRange9 = ssn9.getDataRange();
// get A1 notation identifying the range
var A1Range = SRange1.getA1Notation();
var A1Range1 = SRange1.getA1Notation();
var A1Range2 = SRange2.getA1Notation();
var A1Range3 = SRange3.getA1Notation();
var A1Range4 = SRange4.getA1Notation();
var A1Range5 = SRange5.getA1Notation();
var A1Range6 = SRange6.getA1Notation();
var A1Range7 = SRange7.getA1Notation();
var A1Range8 = SRange8.getA1Notation();
var A1Range9 = SRange9.getA1Notation();
// get the data values in range
var SData1 = SRange1.getValues();
var SData2 = SRange2.getValues();
var SData3 = SRange3.getValues();
var SData4 = SRange4.getValues();
var SData5 = SRange5.getValues();
var SData6 = SRange6.getValues();
var SData7 = SRange7.getValues();
var SData8 = SRange8.getValues();
var SData9 = SRange9.getValues();
// target sheet
var ts = tss.getSheetByName('Sheet1');
function listMajors() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: '1-V0F_pJTKFmP8jRBwpIzBe_sP7GbC-314oUB97N0K-0',
range: A1
}).then(function(response) {
var range = response.result;
if (range.values.length > 0) {
appendPre('Due date, Status, Address:');
for (i = 0; i < range.values.length; i++) {
var row = range.values[i];
appendPre(row[0] + ', ' + row[4]);
function getheaderValues(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet2');
var range = sheet.getRange("A:Z");
var allOfColumnAz = range.getValues()
for (var i = 1; i < 10 ; i++){
var sData = eval("SData"+i);
var lastRow = ts.getLastRow();
var numRows = sData.length;
var numCols = sData[0].length;
ts.getRange(lastRow+(lastRow > 0 ? 2 : 1), 1, numRows, numCols).setValues(sData);
}}

CheckBox for all and for single does not work correctly

I am trying to make an array of listing using checkbox function, the function checks if the all checkbox is clicked then put all listings in the array, if it is clicked to uncheck it pulls all array values, and if a single listing is checked it adds to the array , and if its unchecked when its single or all listing values its value from the array is taken out. Yet on the first run if all selected i cant remove a single value by selecting one checkbox, and after all are checked and unchecked i cant add a single value into array by checking a single option.
var lstsToEdit = [];
lstDisplay("act");
$(".tab-listings-selection").on("click", function() {
var lstType;
if(this.id == "mnLstAct") lstType = "act";
if(this.id == "mnLstInact") lstType = "inact";
if(this.id == "mnLstDraft") lstType = "draft";
document.getElementById("mnLstAct").style.fontWeight = "normal";
document.getElementById("mnLstInact").style.fontWeight = "normal";
document.getElementById("mnLstDraft").style.fontWeight = "normal";
this.style.fontWeight = "bold";
lstDisplay(lstType);
});
function lstDisplay(type){
document.getElementById("main").innerHTML = "";
var tblLsts = document.createElement("table");
tblLsts.setAttribute("id", "tblLsts");
$("#main").append(tblLsts);
var tblLstsHRow = tblLsts.insertRow(0);
var tblLstsHThumb = tblLstsHRow.insertCell(0);
var tblLstsHTitle = tblLstsHRow.insertCell(1);
var tblLstsHStock = tblLstsHRow.insertCell(2);
var tblLstsHPrice = tblLstsHRow.insertCell(3);
var tblLstsHExpiry = tblLstsHRow.insertCell(4);
var tblLstsHSection = tblLstsHRow.insertCell(5);
var tblLstsHAll = tblLstsHRow.insertCell(6);
tblLstsHThumb.outerHTML = "<th></th>";
tblLstsHTitle.outerHTML = "<th>Title</th>";
tblLstsHStock.outerHTML = "<th>In Stock</th>";
tblLstsHPrice.outerHTML = "<th>Price</th>";
tblLstsHExpiry.outerHTML = "<th>Expiry</th>";
tblLstsHSection.outerHTML = "<th>Section</th>";
tblLstsHAll.outerHTML = "<th>All<input id=\"lstsAllChk\" class=\"lstChk\" type=\"checkbox\"/></th>";
var lstThumb = [];
var listings;
if (type == "act") lsts = lstAct;
if (type == "inact") lsts = lstInact;
if (type == "draft") lsts = lstDraft;
for (var lstIndex = 1; lstIndex < lsts.results.length+1; lstIndex++){
var lst = lsts.results[lstIndex-1];
var row = document.getElementById("tblLsts").insertRow(lstIndex);
var colThumb = row.insertCell(0);
var colTitle = row.insertCell(1);
var colStock = row.insertCell(2);
var colPrice = row.insertCell(3);
var colExpiry = row.insertCell(4);
var colSection = row.insertCell(5);
var colSelect = row.insertCell(6);
var lstJ = JSON.parse($.ajax({url: "listings/" + lst.listing_id + ".json", async: false}).responseText);
colThumb.innerHTML = "<img src=\"" + lstJ.results[0].url_75x75 +"\">";
colTitle.innerHTML = lst.title;
colStock.innerHTML = lst.quantity;
colPrice.innerHTML = lst.price;
colSelect.innerHTML = "<input id=\"" + lst.listing_id + "\" class=\"lstChk\" type=\"checkbox\"/>";
for (var secIndex = 0; secIndex < sects.results.length; secIndex++){
if (sects.results[secIndex].shop_section_id == lst.shop_section_id)
colSection.innerHTML = sects.results[secIndex].title;
}
}
$.getScript("tableSort.js");
}
$(".lstChk").on("click", function() {
if(this.id == "lstsAllChk" && this.checked){
for(var lstIndex = 0; lstIndex < document.querySelectorAll(".lstChk").length; lstIndex++){
var lstId = document.querySelectorAll(".lstChk")[lstIndex].id;
//if(lstsToEdit.findIndex( function(value){ value == lstId;}) == -1){;
$("#"+lstId).prop("checked");
lstsToEdit.push(lstId);
//}
}
}
else if(this.id == "lstsAllChk" && !this.checked){
for(var lstIndex = 0; lstIndex < document.querySelectorAll(".lstChk").length; lstIndex++){
var lstId = document.querySelectorAll(".lstChk")[lstIndex].id;
$("#"+lstId).prop("checked", false);
var index = lstsToEdit.findIndex( function(value){ value == lstId;});
lstsToEdit.splice(index, 1);
}
}
else if(this.checked) lstsToEdit.push(this.id);
else {
var index = lstsToEdit.findIndex( function(value){ value == this.id;});
lstsToEdit.splice(index, 1);
}
if(lstsToEdit.length > 0) document.getElementById("lstEdit").style.display = "block";
else document.getElementById("lstEdit").style.display = "none";
console.log(lstsToEdit);
});
table sort js
$("th").on("click", function() {
var table = this.closest("table");
var selection = $(this).text();
var col = this.cellIndex;
var tbl = [];
var order = [];
for (var rowIndex = 0; rowIndex < table.rows.length; rowIndex++){
if (rowIndex > 0){
tbl.push([]);
for (var colIndex = 0; colIndex < table.rows[rowIndex].cells.length; colIndex++){
tbl[rowIndex-1].push(table.rows[rowIndex].cells[colIndex].innerHTML);
if (colIndex == col){
order.push([]);
order[rowIndex-1].push(tbl[rowIndex-1][colIndex]);
order[rowIndex-1].push(rowIndex-1);
}
}
}
}
for (var rowIndex = table.rows.length-1; rowIndex > 0; rowIndex--){
table.deleteRow(rowIndex);
}
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g
order.sort (function (a,b){
var aA = a[0].replace(reA, "").toLowerCase();
var bA = b[0].replace(reA, "").toLowerCase();
if(aA == bA) {
var aN = parseInt(a[0].replace(reN, ""), 10);
var bN = parseInt(b[0].replace(reN, ""), 10);
return aN == bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
};
});
for (var orderIndex = 0; orderIndex < order.length; orderIndex++){
var row = table.insertRow(orderIndex + 1);
for (var colIndex = 0; colIndex < tbl[orderIndex].length; colIndex++){
var cell = row.insertCell(colIndex);
var index = order[orderIndex][1];
cell.innerHTML = tbl[index][colIndex];
}
}
});
index
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
include 'menu.php';
include 'shopJson.php';
?>
<div id="lstEdit">edit</div>
<div id="main"></div>
</body>
</html>
<script>
var lstActURL = "listings/active.json";
var lstInactURL = "listings/inactive.json";
var lstDraftURL = "listings/draft.json";
var sectURL = "listings/sect.json";
var lstAct = JSON.parse($.ajax({url: lstActURL, async: false}).responseText);
var lstInact = JSON.parse($.ajax({url: lstInactURL, async: false}).responseText);
var lstDraft = JSON.parse($.ajax({url: lstInactURL, async: false}).responseText);
var sects = JSON.parse($.ajax({url: sectURL, async: false}).responseText);
$("#mnLstAct").append("(" + lstAct.results.length + ")");
$("#mnLstInact").append("(" + lstInact.results.length + ")");
$("#mnLstDraft").append("(" + lstDraft.results.length + ")");
document.getElementById("mnLstAct").style.fontWeight = "bold";
$.getScript("listings.js");
</script>
The JQuery .attr() method correlates to the actual attributes of a DOM element. However, from the JavaScript perspective, many elements have DOM properties that seem like they are the same as their HTML attribute counterparts, but are not because the property is updated in memory, while the attribute change updates the DOM. Sometimes, there are properties that don't even have an attribute counterpart (i.e. selectedIndex on select elements).
The point is that you have thess lines:
$("#"+lstId).attr("checked", true);
$("#"+lstId).attr("checked", false);
Where you are attempting to force an element to be checked, but that may not correlate to what you get when you check the checked property.
To account for this, use the prop() method instead of the .attr() method:
$("#"+lstId).prop("checked", true);
$("#"+lstId).prop("checked", false);
See the documentation for .prop() for details and a comparison between attributes and properties.

Get Unique values during Loop

I am looping through an array and getting the data that I need.
for (var i = 0; i < finalArray.length; i++) {
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
var transAccount = finalArray[i].transAccount;
}
What I am trying to do at this point is only show unique data in the loop.
For example var transAccount could be in the array 5 times. I only one to display that in my table once. How can I go about accomplishing this ?
Final Array is constructed like so; just as an object:
finalArray.push({
transID: tmpTrans,
transAccount: tmpAccount,
amEmail: amEmail,
merchName: merchName,
amPhone: amPhone,
amName: amName
});
var allTransAccount = {};
for (var i = 0; i < finalArray.length; i++) {
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
var transAccount = finalArray[i].transAccount;
if(allTransAccount[finalArray[i].transAccount]) {
var transAccount = '';
}
else {
allTransAccount[transAccount] = true;
}
}
var merhcData = {};
var amName = {};
// and so on
for (var i = 0; i < finalArray.length; i++) {
merchData[finalArray[i].merchName] = finalArray[i].merchName;
amName[finalArray[i].amName] = finalArray[i].amName;
// and so on
}
If you are sure, that data in merchName will never be equal amName or other field - you can use one data object instead of several (merchData, amName...)
What you want is likely a Set. (see zakas for ES6 implementation. To emulate this using javascript, you could use an object with the key as one of your properties (account would be a good bet, as aperl said) which you test before using your raw array.
var theSet={};
for (var i = 0; i < finalArray.length; i++) {
var transAccount = finalArray[i].transAccount;
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
if(!theSet[transAccount]){
//add to your table
theSet[transAccount]===true;
}
This will prevent entries of duplicate data.

Categories

Resources