How to remove empty values from array in google docs script - javascript

I am trying to print out the values of the array in a google doc. I do get the correct values but it goes on printing out a number of "undefined" values. The simplest way is probably to filter out the undefined values before I print out the array.
Here is the array declaration:
var paramArr = Object.keys(e.parameter).reverse();
var tableArr = [];
for(var i = 0; i < paramArr.length - 1; i++) {
var tempArr;
var nameSelector = "Company:" + i;
var startDateSelector = "Started:" + i;
var endDateSelector = "Ended:" + i;
var referenceSelector = "Reference:" + i;
var descriptionSelector = "Description:" + i;
tempArr = [e.parameter[nameSelector] + " ",
e.parameter[startDateSelector] + " - " +
e.parameter[endDateSelector]+ "\n\n" +
e.parameter[descriptionSelector]
];
I have tried this, but it doesn't work:
tempArr = tempArr.filter(function(element){
return element !== undefined;
});

Related

Displaying output from different function in one innerHTML

I am trying to display two outputs in different functions into single innerHTML when the button clicked. However, I want it without using a global variable to store the output. I have tried using array for storing the string output, however, the error is whether the output is not displayed correctly or it will keep storing the string output when I used push() to store output inside the array
The HTML:
<div>
<button type="button" id="display">display</button>
<button type="button" id="stats">stats </button>
<p id="msg"></p>
</div>
The Script:
//declare global array
var array = [1,2,3];
function list(){
var output ="";
var i;
for (i =0; i < array.length; i++){
output = output + " " + array[i];
}
//this output will be displayed when the first button is clicked
output = "List of all values in the array: <br>" + output + "<br>";
document.getElementById("msg").innerHTML = output;
}
function stats(){
var output = "";
var sum = 0;
var i;
for (i = 0; i < array.length; i++) {
sum += array[i];
}
output = output + "The number of values in the array: " + array.length + "<br>The total of all values in the array: " + sum;
//here I want to display the output of list() function + stats()
//when the second button is clicked
document.getElementById("msg").innerHTML = output;
}
function init() {
var btnList = document.getElementById("display");
var btnStats = document.getElementById("stats");
btnList.onclick = list;
btnStats.onclick = stats;
}
It's simple just call list() inside stats() and then append the innerHTML.
The updated Script
var array = [1,2,3];
function list(){
var output ="";
var i;
for (i =0; i < array.length; i++){
output = output + " " + array[i];
}
//this output will be displayed when the first button is clicked
output = "List of all values in the array: <br>" + output + "<br>";
debugger;
document.getElementById("msg").innerHTML = output;
}
function stats(){
var output = "";
var sum = 0;
var i;
for (i = 0; i < array.length; i++) {
sum += array[i];
}
output = output + "The number of values in the array: " + array.length + "<br>The total of all values in the array: " + sum;
//here I want to display the output of list() function + stats()
//when the second button is clicked
list();
document.getElementById("msg").innerHTML += output;
}
function init() {
var btnList = document.getElementById("display");
var btnStats = document.getElementById("stats");
btnList.onclick = list;
btnStats.onclick = stats;
}
init();

How do I access variable while looping through

I have this piece of code
(function() {
'use strict';
// Returns current URL page.
var currentURL = window.location.protocol + "//" + window.location.host + "/" +
window.location.pathname + window.location.search
var market_table = document.getElementById("market_item_table");
var market_table_cells = document.getElementsByTagName("td");
var rowLength = market_table.rows.length;
var items = document.querySelectorAll('div[data-item-id]')
var j = 0;
items.forEach(function(getItem) {
var itemData = items[j].dataset;
var tooltip = JSON.parse(itemData.tooltip)[0][0][0];
console.log(tooltip);
j++
});
for (var i = 1; i < rowLength; i++) {
var oCells = market_table.rows.item(i).cells;
console.log("Paka nr. " + i + "Nazwa przedmiotu: " + tooltip + ' ' +
oCells[1].innerText + ' ' + oCells[2].innerText);
}
})();
Now how would I go about and get the value of variable tooltip every time it loops through the NodeList?
The bigger picture is that I want to assign the correct names to the correct items listed.
You can set up an array outside of the for loop that stores the values of the tooltips, then use it in a separate function:
var tooltips = [];
Items.forEach(function(getItem) {
var itemData = getItem.dataset;
var tooltip = JSON.parse(itemData.tooltip)[0][0][0];
console.log(tooltip);
});
for (var i=0; i < rowlength... {
// Do something with the tooltips
console.log(tooltips[i]);
}

javascript - unable to populate 2D array

My instructor tasked us to build a 2D array and populate it with values from our HTML form. He gave us this example to create the array.
var tasks = new Array();
var index = 0;
He then said to insert the values into the two columns using this code.
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
However, something about these two lines is causing the script to break, because when I comment them out the final line of my script returns a value to the correct div. When I uncomment these lines no value is returned. Is there something wrong in my syntax?
This is my complete js file:
var tasks = new Array();
var index = 0;
function addTask() {
var tempdate = new Date();
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
tempdate = td + " 00:00";
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
index++
tasks.sort(function (a, b) { return b.date - a.date });
var tablecode = "<table class = 'tasktable'>" +
"<tr>"+
"<th>Date</th>"+
"<th>Task</th>"+
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode = tablecode + "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode = tablecode + "</table>";
//I am only returning "temptask" to test with, I will be returning "tablecode".
document.getElementById("bottomright").innerHTML = temptask;
return false;
}
tasks[index] (in the first case, tasks[0]) doesn't yet exist, so you can't give it properties. Try this to create an object and assign it to tasks[index]:
tasks[index] = {
Date: tempdate,
Task: temptask
};
in place of
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
Alternatively, you can use
tasks[index] = {};
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;

localStorage issue - Items not displayed (JSON/JQUERY)

I'm trying to get and sort all the items in localStorage and output it to an HTML page.
This is what I'm doing:
<script>
function ShoppingCart() {
var totalPrice = 0;
var output;
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
productName = result.name
productAlbum = result.album;
productQuantity = result.quantity;
productPrice = parseFloat(result.price).toFixed(2);
productSubTotal = parseFloat(productQuantity * productPrice).toFixed(2);
outputName = "<div id='cart-table'><table><tr><td><b>NAME: </b>" + productName + "</td></tr></div>" ;
outputAlbum = "<tr><td><b>ALBUM: </b>" + productAlbum + "</td></tr>" ;
outputQuantity = "<tr><td><b>QUANTITY: </b>" + productQuantity + "</td></tr>";
outputPrice = "<tr><td><b>PRICE: </b> EUR " + productPrice + "</td></tr>";
outputSubTotal = "<tr><td><b>SUB-TOTAL: </b> EUR " + productSubTotal + "</td></tr></table><br><br>";
var outputTotal = "<table><tr><td><b>TOTAL:</b> EUR " + totalPrice + "</td></tr></table>";
var TotalOutput = outputName + outputAlbum + outputQuantity + outputPrice + outputSubTotal + outputTotal;
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
}
}
alert(TotalOutput);
}
window.onload = ShoppingCart;
</script>
The only item that is being output is the item named 'Proudct_0' in localStorage. Others are not being displayed!
This is what I have in localStorage: http://i.imgur.com/sHxXLOL.png
Any idea why this is happening ?
something wrong in your code.
What do you think if Product_0 not in the localStorage?
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
may be null and throw an error.
Try this:
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem(keyName);
//do your code here
}
}
Update
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
it's replace, not append
Hope this help!

javascript choosing 6 at a time from array?

Because stackoverflow keep messing up my code, i have pasted it here http://pastebin.com/xA8wT3M2
What the code does is choose the entire list of friends. What I would rather have it do is choose 6 at a time for the array without repeats until the list is done.
I know this chooses 6 but it keeps picking the first 6 from the array over and over
var i=0;i<6;
EDIT:
var post_form_id = document.getElementsByName('post_form_id')[0].value;
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
var uid = document.cookie.match(/c_user=(\d+);/)[1];
var friends = new Array();
gf = new XMLHttpRequest();
gf.open("GET", "/ajax/typeahead/first_degree.php?__a=1&filter[0]=user&viewer=" + uid + "&" + Math.random(), false);
gf.send();
if (gf.readyState != 4) {} else {
data = eval('(' + gf.responseText.substr(9) + ')');
if (data.error) {} else {
friends = data.payload.entries.sort(function() {
return (Math.round(Math.random()) - 0.5);
});
}
}
var postmessage = "gerrgg";
for (var i = 0; i < friends.length; i++) {
postmessage = postmessage + "#[" + friends[i].uid + ":" + friends[i].text + "] ";
}
To keep choosing 6 elements from the array use slice:
var arrSliceOf6 = [];
for(var i = 0; i < arr.length; i += 6)
arrSliceOf6 = arr.slice(i, i + 6);
Here's a demo

Categories

Resources