I need to convert the table grid i created into an multidimensional array according to the content inside the table. Array would be in format like:
var array = [
[column,column,...],
[column,column,...],
...
];
How do I do this without using jQuery, using plain JavaScript? All answers I found was in jQuery.
JSFiddle.
With qSA and Array.prototype.map is pretty simple.
var tableInfo = Array.prototype.map.call(document.querySelectorAll('#tableId tr'), function(tr){
return Array.prototype.map.call(tr.querySelectorAll('td'), function(td){
return td.innerHTML;
});
});
Presuming your table is something like the one below, you can convert that into an array of arrays using the rows collection of the table and cells collection of the rows:
function tableToArray(table) {
var result = []
var rows = table.rows;
var cells, t;
// Iterate over rows
for (var i=0, iLen=rows.length; i<iLen; i++) {
cells = rows[i].cells;
t = [];
// Iterate over cells
for (var j=0, jLen=cells.length; j<jLen; j++) {
t.push(cells[j].textContent);
}
result.push(t);
}
return result;
}
document.write(JSON.stringify(tableToArray(document.getElementsByTagName('table')[0])));
<table>
<tr>
<td>one<td>two<td>three
<tr>
<td>one<td>two<td>three
<tr>
<td>one<td>two<td>three
</table>
Or if like concise code, use some ES5 goodness:
function tableToArray(table) {
var result = [].reduce.call(table.rows, function (result, row) {
result.push([].reduce.call(row.cells, function(res, cell) {
res.push(cell.textContent);
return res;
}, []));
return result;
}, []);
return result;
}
you can get all the tr inside a table (having id table1) by doing
var tableObj = document.getElementById( "table1" );
var arr = [];
var allTRs = tableObj.getElementsByTagName( "tr" );
for ( var trCounter = 0; trCounter < allTRs.length; trCounter++ )
{
var tmpArr = [];
var allTDsInTR = allTRs[ trCounter ].getElementsByTagName( "td" );
for ( var tdCounter = 0; tdCounter < allTDsInTR.length; tdCounter++ )
{
tmpArr.push( allTDsInTR[ tdCounter ].innerHTML );
}
arr.push( tmpArr );
}
console.log( arr );
Run a for loop through the rows and the fields:
var array = [];
var table = document.querySelector("table tbody");
var rows = table.children;
for (var i = 0; i < rows.length; i++) {
var fields = rows[i].children;
var rowArray = [];
for (var j = 0; j < fields.length; j++) {
rowArray.push(fields[j].innerHTML);
}
array.push(rowArray);
}
console.log(array);
JSfiddle.
Related
I've been trying to get this data, but the array comes out empty:
function saveData() {
var tableData = [];
var table = document.getElementById("dtable");
console.log(table)
for (var i = 0; i < table.length; i++) {
let tableCells = table.rows.item(i).cells;
let cellLength = tableCells.length;
for (let j = 0; j < cellLength; j++) {
let cellVal = tableCells.item(j).innerHTML;
tableData.push(cellVal)
}
}
console.log(tableData)
rows = JSON.stringify(tableData);
google.script.run.formToSheets(rows);
}
Thanks for any help!
In your script, as one of several possible modifications, how about the following modification?
From:
var tableData = [];
var table = document.getElementById("dtable");
console.log(table)
for (var i = 0; i < table.length; i++) {
let tableCells = table.rows.item(i).cells;
let cellLength = tableCells.length;
for (let j = 0; j < cellLength; j++) {
let cellVal = tableCells.item(j).innerHTML;
tableData.push(cellVal)
}
}
console.log(tableData)
To:
var table = document.getElementById("dtable");
console.log(table)
var [, ...tr] = table.querySelectorAll("tr");
var tableData = [...tr].map(r => {
var td = r.querySelectorAll("td");
return [...td].map((c, j) => j != 3 ? c.innerHTML : c.querySelectorAll("select")[0].value);
});
console.log(tableData)
In this modification, from a table, the table rows are retrieved. And, the table cells are retrieved from the table rows. In teh case of the dropdown list, the value is retrieved from the dropdown list.
Note:
When this modification was not the direct solution to your issue, I think that when you provide your whole script, it will help to correctly understand your question.
Given a table such as this, how do you convert it to a table where every column and every row takes up one slot instead of many. I am trying but it's pretty difficult to wrap my head around.
var r = document.querySelectorAll('table tbody tr')
var w = []
var matrix = []
var rows = []
for (var i = 0, n = r.length; i < n; i++) {
rows.push([])
}
var c, b
for (var i = 0, n = r.length; i < n; i++) {
var x = r[i]
var d = x.querySelectorAll('td')
for (var j = 0, m = d.length; j < m; j++) {
var y = d[j]
while (b--) {
var column = y
row.push(column)
}
if (c > 0) {
rows[i].push()
c--
}
b = parseInt(y.getAttribute('colspan') || 1)
c = parseInt(y.getAttribute('rowspan') || 1)
}
}
function c1(el) {
}
I'm just considering the tbody part.
If I understood your question correctly, are you looking for something of this kind?
const myTable = document.querySelector('#my-Table tbody')
var matrix = []
for (let r=0; r<myTable.rows.length; r++ )
{
matrix[r] = []
for (let c=0;c<myTable.rows[r].cells.length; c++ )
{
matrix[r][c] = myTable.rows[r].cells[c].colSpan
}
}
Run this on that wikipedia page and tell me if that's what you're looking for. At least for columns.
const tds = [];
for (let td of document.querySelectorAll(`td, th`)) {
tds.push(td);
}
for (let td of tds) {
//debugger;
const colspan = td.getAttribute(`colspan`);
if (colspan) {
td.setAttribute(`colspan`, 1);
for (let i = 1; i <= colspan - 1; i++) {
td.after(document.createElement(`td`));
}
}
}
Edit: I see now that rows are much harder. (if this is what you want)
Which server side language are you using ?
Usually for these, you could just have a form which is posting data to another website's form. Look at this php example : https://www.ostraining.com/blog/coding/retrieve-html-form-data-with-php/
Correct me If I did not understand your question correctly.
This is what I was looking for.
print('.wikitable2')
function print(selector) {
var matrix = parse(selector)
var table = []
matrix.forEach(arr => {
arr = arr.map(x => x.replace(/,/g, ';'))
table.push(arr.join(','))
})
console.log(table.join('\n'))
}
function parse(selector) {
var rowEls = document.querySelectorAll(selector + ' thead th, ' + selector + ' tbody tr')
var matrix = []
for (var i = 0, n = rowEls.length; i < n; i++) {
var rowEl = rowEls[i]
var cellEls = rowEl.querySelectorAll('td, th')
var y = 0
for (var j = 0, m = cellEls.length; j < m; j++) {
var cellEl = cellEls[j]
var rowSpan = parseInt(cellEl.getAttribute('rowspan') || 1)
var cellSpan = parseInt(cellEl.getAttribute('colspan') || 1)
var val = parseCell(cellEl, j)
var rowSpanIterator = rowSpan
while (rowSpanIterator--) {
var cellSpanIterator = cellSpan
while (cellSpanIterator--) {
var x = i + rowSpanIterator
matrix[x] = matrix[x] || []
matrix[x][y + cellSpanIterator] = val
}
}
y += cellSpan
}
}
return matrix
}
function parseCell(el, i) {
return el.textContent.trim()
}
Hey i have a simple question i cant find an answer,
i´m trying to generate some raw-data for a chart
lets say i have an array like :
[1,0,0,1,2,0]
is there a way to make an array out of it that has nested arrays that represent the count of duplicate entrys ?
[[0,3],[1,2],[2,1]]
here is some code that does the trick, but saves the count as objects
var array = [1,0,0,1,2,0];
var length = array.length;
var objectCounter = {};
for (i = 0; i < length; i++) {
var currentMemboerOfArrayKey = JSON.stringify(array[i]);
var currentMemboerOfArrayValue = array[i];
if (objectCounter[currentMemboerOfArrayKey] === undefined){
objectCounter[currentMemboerOfArrayKey] = 1;
}else{
objectCounter[currentMemboerOfArrayKey]++;
}
}
but objectCounter returns them like
{0:3,1:2,2:1}
but i need it as an array i specified above ?
for any help, thanks in advance
Try
var array = [1, 0, 0, 1, 2, 0];
function counter(array) {
var counter = [],
map = {}, length = array.length;
$.each(array, function (i, val) {
var arr = map[val];
if (!arr) {
map[val] = arr = [val, 0];
counter.push(arr);
}
arr[1] += 1;
})
return counter;
}
console.log(JSON.stringify(counter(array)))
Demo: Fiddle
You can turn your object into an array easily:
var obj = {0:3,1:2,2:1};
var arr = [];
for (var key in obj) {
// optional check against Object.prototype changes
if (obj.hasOwnProperty(key)) {
arr.push([+key, obj[key]]);
}
}
Note: The object keys are strings, so i converted them back to numbers when placed in the array.
Functional way of doing this, with Array.reduce and Array.map
var data = [1,0,0,1,2,0];
var result = data.reduce(function(counts, current) {
counts[current] = current in counts ? counts[current] + 1: 1;
return counts;
}, {});
result = Object.keys(result).map(function(current){
return [parseInt(current), result[current]];
});
console.log(result);
Output
[ [ 0, 3 ], [ 1, 2 ], [ 2, 1 ] ]
Try:
var data = [1,0,0,1,2,0];
var len = data.length;
var ndata = [];
for(var i=0;i<len;i++){
var count = 0;
for(var j=i+1;j<len;j++){
if(data[i] == data[i]){
count ++;
}
}
var a = [];
a.push(data[i]);
a.push(count);
ndata.push(a);
}
console.log(ndata)
DEMO here.
First you need to map the array to an associative object
var arr = [1,0,0,1,2,0];
var obj = {};
for (var i = 0; i < arr.length; i++) {
if (obj[arr[i]] == undefined) {
obj[arr[i]] = 0;
}
obj[arr[i]] += 1;
}
Then you can easily turn that object into a 2d matrix like so:
arr = [];
for (var k in obj) {
arr.push([k, obj[k]]);
}
alert(JSON.stringify(arr));
Your existing object can be turned into an array with a simple for..in loop. Also your existing code that produces that object can be simplified. Encapsulate both parts in a function and you get something like this:
function countArrayValues(array) {
var counter = {},
result = [];
for (var i = 0, len = array.length; i < len; i++)
if (array[i] in counter)
counter[array[i]]++;
else
counter[array[i]] = 1;
for (i in counter)
result.push([+i, counter[i]]);
return result;
}
console.log( countArrayValues([1,0,0,1,2,0]) );
Demo: http://jsfiddle.net/hxRz2/
I'm looping through a set of inputs. I need to tally up the grouped totals.
var compoundedArray = new Array();
holder.find(".dataset input").each(function(index) {
var val = $(this).val();
var dataType = $(this).data("type");
var localObj = {};
localObj[dataType] = val;
compoundedArray.push(localObj);
});
I have an object like this
[
{
"growth":30
},
{
"growth": 40
},
{
"other": 20
}
]
how do I loop through the object to produce something like
[
{
"growth": 70
},
{
"other": 20
}
]
if I looped over the initial array object
for (var i = 0; i < compoundedArray.length; i++) {
console.log(compoundedArray[i]);
}
how would I go about checking to ensure I don't have duplicates - and that I can tally up the results?
I think your selection of data structure is a bit too complicated. Try something like.
var compoundedObject = {};
holder.find(".dataset input").each(function(index) {
var val = $(this).val();
var dataType = $(this).data("type");
//Assuming all values are integers and can be summed:
if( compoundedObject.hasOwnProperty(dataType) )
{
compoundedObject[dataType] += val;
}
else
{
compoundedObject[dataType] = val;
}
});
You will end up with an object, not an array though.
var add=function (a,b){ a=a||0; b=b||0; return a+b};
var input=[ {growth:30},{growth:40},{other:20} ],output=[],temp={};
$.each(input,function(i,o){
var n;
for(i in o)
{n=i;break}
temp[n]=add(temp[n],o[n]);
});
$.each(temp,function(i,o){
var k={};
k[i]=o;
output.push(k)
});
find output at output variable.
Do not post much specific question, It might not help others.
This works. And it's pure javascript.
var totals = {};
for (var i = 0; i < compoundedArray.length; i++) {
var item = compoundedArray[i];
for (var key in item) {
totals[key] = (totals[key] || 0) + item[key]
}
};
You can loop trough an Object with a for loop.
If you want to delete an item simply set it to null.
Example:
for(var i in compoundedArray){
for(var j in compoundedArray){
if(i == j){
compoundedArray[i] += compoundedArray[j];
compoundedArray[j] = null;
}
}
}
You can do the following:
var totals = [], tmp = {};
for (var i = 0; i < compoundedArray.length; i++) {
var obj = compoundedArray[i];
for (var j in obj) {
tmp[j] = tmp[j] || 0;
tmp[j] += obj[j];
}
}
for(var k in tmp) {
var obj = {};
obj[k] = tmp[k];
totals.push(obj);
}
See this working demo
how to insert values in a html table, an array multidimensional in javascript.
Additionally, such as performing calculations between the columns of the array and insert the results into a column of the same array.
thanks for your answers.
Javascript code:
var multiArray;
window.onload = function() {
// load the table into the multidimensional array.
multiArray = [];
var trs = document.getElementsByTagName('TR');
for(var i = 0; i < trs.length; i++) {
var arr = [];
var tds = trs[i].childNodes;
for(var j = 0; j < tds.length; j++) {
var td = tds[j];
if (td.tagName === 'TD') {
arr.push(td.innerHTML);
}
}
multiArray.push(arr);
}
// perform some calculations between the columns of the array
var resCalc = [];
for(i = 0; i < multiArray.length; i++) {
resCalc[i] = 0;
for(j = 0; j < multiArray[i].length; j++) {
resCalc[i] += multiArray[i][j];
}
}
// insert the results into a column of the same array
var columnToModify = 0; // the index of the column you want to change
for(i = 0; i < multiArray.length; i++) {
multiArray[i][columnToModify] = resCalc[i];
}
};
something on Google…
http://www.eggheadcafe.com/community/aspnet/3/10003047/html-table-in-to-an-array.aspx