convert a html table to a 2D array with numbers with javascript - javascript

I use the below JavaScript function to generate a html table from a 2D data array with numbers called d.
function matrix(d) {
var html = '<table>';
for (var i = 0; i < d.length; i++) {
html += '<tr>';
for (var j = 0; j < d[i].length; j++) {
html += '<td>' + d[i][j] + '</td>';
}
html += "</tr>";
}
return html;
}
That function works well but I can only look at the pretty html output and not use the data in other functions so now I am trying to write another function that goes in the opposite direction and converts a html table to a 2D array with numbers. So far I got the below function:
function tableToArray(w) {
var myTableArray = [];
$(w).each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
console.log(myTableArray);
return myTableArray;
}
but that function is not working very well. If I call tableToArray(matrix([[1,2,3],[4,5,6]])) the result in the console.log is a 1D column array with strings (or maybe a 1D row array with string hard to tell the difference in the console log) that looks like "1","2","3","4","5","6". I want a 2D array with numbers and not strings since my original array was a 2D array with numbers. What JavaScript function code will give me that 2D array with numbers?
Assigning the data array d to a global variable (without var) or a window.variable is not an option because I need to be able to call the function likes this: tableToArray(matrix([[1,2,3],[4,5,6]])).
I have googled around all day to find a previous written function that does this but I have not managed to find a working one nor have I been successful in writing one myself.

Related

Displaying total array elements for array being built by form

I'm currently in a JavaScript course that is asking me to have the following happen:
User enters names one at a time into a form, then presses Submit
The names are stored into an array and output to a table
As names are entered (and added to the table), a total must update as well--based on the array, not just from counting table elements
My current issue is I'll add one name, then the total shows "1"--when I add a second name, the total displays "11"
This is currently what my JavaScript code looks like:
function displayNamesAndTotal() {
// Your code goes in here.
var userInputName = [];
var totalNamesEntered = [];
var countTotal = 0;
var firstName;
var arrayIndex;
var output;
var outputTotal;
var form;
form = document.getElementById("userFormId");
output = document.getElementById("userEntriesId");
outputTotal = document.getElementById("testId");
//userInputName[0] = form.firstname.value;
userInputName.push(form.firstname.value)
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
output.innerHTML += "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
countTotal += userInputName.length;
}
outputTotal.innerHTML += countTotal;
return false;
}
I've spent the past day or so trying to figure out what I'm doing wrong--and it's probably something embarrassingly easy--but I'm at a loss and could use guidance
Any suggestions?
Thanks
It looks like your total is storing a string instead of a number. Try using parseInt(number) to convert the string into a number.
Good grief, from reading the other answers from you guys I think I have it licked
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
tableData = "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
totalCount = userInputName.length;
}
output.innerHTML += tableData;
outputTotal.innerHTML = "<h4>Total Number of Strings: " + totalCount + "</h4>";
form.string.select();
return false;
This way the totalCount acted as the array's length when it went through the loop, then outside in the innerHTML statement I could display it and have it constantly update whenever a new string was submitted.
Thank you for all of your feedback
outputTotal.innerHTML is a string, so adding to it would concatenate the strings together. Since outputTotal.innerHTML starts out as null, add 1 to it creates "1". When you add 1 to it again, outputTotal.innterHTML is already "1", so it becomes "11".
Instead of incrementing outputTotal.innerHTML try setting the HTML to it directly.
outputTotal.innerHTML = countTotal;

Sorting of XML data with Javascript

I need some help with JavaScript.I am working with XML so i need on which i am implementing JavaScript, and i would like to do sorting of the elements node name. Please see the following figure which will make you clear what i am talking about. Please i want the code with JavaScript not Jquery.
Live Fiddle
UnSorted: Sorted:
bookstore bookstore
xbook abook
title author
author price
year title
price year
cbook cbook
gbook gbook
abook xbook
function generate(node) {
if (node.nodeType != 1) return "";
var html = "<li>" + node.nodeName;
var htmlForChildNodes = "";
for (var i = 0; i < node.childNodes.length; i++) {
htmlForChildNodes += generate(node.childNodes[i]);
}
if (htmlForChildNodes) {
html += "<ul>" + htmlForChildNodes + "</ul>";
}
html += "</li>";
return html;
}
Thank you
You should parse the xml document and put it into a javascript array of objects. Those are easily sortable.
So instead of calling generate(xmlDoc.documentElement) and have it return html straight from the xml you should add a parse(xmlDoc.documentElement) function that returns an array of arrays. After that change your generate() function to take an object with a children property that is an array instead of the original xml dom.
Parse should look something like this:
function parse(node) {
if (node.nodeType != 1) return null;
var result = {name: node.nodeName};
var children = [];
for (var i = 0; i < node.childNodes.length; i++) {
var child = parse(node.childNodes[i]);
if (child)
{
children.push(child);
}
}
result.children = children;
return result;
}
Now you can sort the arrays with children by creating your own comparator function.
After sorting you call the (changed) generate() function that will iterate over the objects/arrays to produce the html.
Here is a fiddle. I've left the changes of the generate() function to you. (Use your browser console to inspect the generated data structure)

concatenate an increment counter onto the end of an array selector within a json response loop

so I'm looping through a json response and I'm trying to use the counter (var i) to say data.newarray[i].time+i so with each loop the next array is chosen and the time also increases in number. So 1st loop will spit out data.newarray[0].time0 then data.newarray[1].time1 then data.newarray[2].time2 and so on. The bit that is currently failing is my concatenation time+i at the end. How do I format this to work?
var data = JSON.parse(xmlHTTP.responseText);
for(var i=0; i<data.newarray.length; i++)
{
alert(data.newarray[i].time+i);
}
You can access variable property names by using the quoted notation: obj['prop'] instead of obj.prop.
The solution is:
var data = JSON.parse(xmlHTTP.responseText);
for(var i=0; i<data.newarray.length; i++)
{
alert(data.newarray[i]['time'+i]);
}
Try something like this:
for(var i=0; i<data.newarray.length; i++) {
alert(data.newarray[i]['time'+i]);
}

Log input into array, print only new input

Okay I have a a couple of functions. I don't think most of them are relevant. What I want to do is create an html list when you click a button, and store the value in an array. However I want to be able to update this list without outputting the entire array again. I have it set up to accept the input and I can get it to loop and print the array but it will print the entire array and I only want one. This seems like a common thing but my Google-fu returned nothing.
So I have a list variable that connects to an input, logs it into an array, and another function to clear it and print out the values.
Code snippet:
var listItemInput= document.getElementByID("listItem");
var listItem= [];
function insertListItem(){
listItem.push(listItemInput.value);
clearAndShow();
}
function clearAndShow(){
listItemInput.value= "";
}
function printList{
for (var i = 0; i < listItem.length; i++){
document.getElementById("list").innerHTML += '<li>' + listItem[i] + '</li>';
}
When the printList funciton is called by pressing the button it prints the entire array over however I would like a button that simply prints the newest item. How could I do that?
For clarification, I need to print out the list to html and store the values in an array, the values will later be referenced in an if else argument to combine and print them with new variables.
EDIT:
I plugged in the var = lastIndex and changed it as well as made two more variables for my list. This seems to make it work. Thank you.
You could keep track of the last index printed.
var listItemInput= document.getElementByID("listItem");
var listItem = [];
var lastIndex = 0; //Keep track of the last index shown.
function insertListItem() {
listItem.push(listItemInput.value);
clearAndShow();
}
function clearAndShow() {
listItemInput.value = "";
}
function printList() {
for (; lastIndex < listItem.length; lastIndex++) {
document.getElementById("list").innerHTML += '<li>' + listItem[lastIndex] + '</li>';
}
}
This approach assumes you won't be removing items from listItem array, which you didn't express is something that would be done.
If you only want one element, why do you need to iterate?
function printList() {
document.getElementById('list').innerHTML = '<li>' + listItem[listItem.length-1] + '</li>';
}

How to iterate an array and acces a map using Handlebars?

I have data structures similar to the code below that I want to iterate through with Handlerbars. While the javascript code that can do this iteration is clear, I have not been able to figure out how to do it in handlebars.
var keys = ['key1','key2','key3']
var map = {'key1':{...}, 'key2':{...}, 'key3':{...}, .... 'keyN': {...}}
What I want to do within handlebars is to iterate the keys array and use the value from the keys array to look-up the object from the map. Can this be done without writing a helper?
UPDATE I know how to write the code in javascript, I want to do is "what i can do in raw js using handlebarJS expressions".
try this :
for(var i=0; i<keys.length; i++){
console.log(map[keys[i]])
}
Handlebars.registerHelper('list', function(keys, maps) {
var out = "<ul>";
for(var i=0, i=keys.length; i++) {
out = out + "<li>" + map[keys[i]] + "</li>";
}
return out + "</ul>";
});

Categories

Resources