get array of arrays looping through HTML table - javascript

I have this bunch of code
var rows = document.querySelectorAll('.workRow')
var codes = []
for(var i=0;i<rows.length;i++){
var timeCodesInputs = rows[i].getElementsByClassName('xCell')
for(var j=0;j<timeCodesInputs.length;j++){
if(timeCodesInputs[j].innerHTML == "x"){
codes.push(timeCodesInputs[j].dataset.dataHour)
}
}
}
it works ok but it pushed everything to one array. What I want to get an array of arrays where one array if the data from one row. How to do it?

Ciao, try to push row data in one array and then push this array into codes array like:
var rows = document.querySelectorAll('.workRow')
var codes = []
for(var i=0;i<rows.length;i++){
var rowArray = [];
var timeCodesInputs = rows[i].getElementsByClassName('xCell')
for (var j=0;j<timeCodesInputs.length;j++){
if(timeCodesInputs[j].innerHTML == "x"){
rowArray.push(timeCodesInputs[j].dataset.dataHour)
}
}
codes.push(rowArray)
}

Related

Combining 2D Array with Key-Value Array

I have an array where each row is an array that has 2 values, S/N and Description.
array1 = [["xx9","Big Car"],["xx1","Small Car"],["xx9","Big Car"],["xx9"," Big Car"]];
As you can see there are duplicates. So I wrote code that creates a count array that holds the key-value pairs and counts each item. Length of count is 1.
count = [xx1: 1
xx9: 3]
So now I want to combine the two arrays into one new one that includes the quantity, in this example the final output would be as shown below. Note that I have to also remove the duplicates in array1. Order doesn't matter.
final_array = [["1","xx1","Small Car"],["3",xx9","Big Car"]];
Here is my JS code so far but basically the .forEach loops won't work over the count array. Can anyone help me so that this code works on the key-value array.
JS/Jquery:
//Pull the Cart Data & Orangize
var savedList = JSON.parse(localStorage.getItem("partList"));
console.log(savedList);
determineQuantity(savedList); //Count quantity of each item
//Count the Quantity of each item in saved list & create key-value pairs
function determineQuantity(savedList){
var newList = [];
var count = [];
for (var i=0, j = savedList.length; i<j; i++){
count[savedList[i][0]] = (count[savedList[i][0]] || 0) + 1;
};
console.log(count);
//Combine Quantity Array with SavedList Array
count.forEach(function(item,index){
console.log("index = " + index + " item = " + item);
savedList.forEach(function(row){
if ($.inArray(item,row == 0)){ //if found in this row at index 0
var new_part = [count[index],row[0],row[1]];
console.log("new_part = " + new_part);
newList.push(new_part);
};
});
});
console.log(newList);
};
how about this.
var test = function(){
var array = [["xx9","Big Car"],["xx1","Small Car"],["xx9","Big Car"],["xx9"," Big Car"]];
var count = {xx1: 1, xx9: 3};
var map = {};
array.forEach(function(item){map[item[0]] = item[1]});
var newArray = [];
for(var key in count){
if(!map[key])
continue;
newArray.push([count[key], key, map[key]]);
}
console.log(newArray);
}
first of all, you count is a object, not a array. then we dont need forEach

Split multiple arrays into strings, skipping empty arrays

I've made an AJAX call that has returned 20 arrays, some of which are empty, and others that have one or more items in them. I've split each array into strings using a for loop. The only problem is that this creates lots of empty strings from the arrays that were empty. Is there a way that I could skip the empty arrays in my for loop?
success: function(data){
console.log(data);
for(x in data.data){
var hashArray = data.data[x].tags;
var hashStrings = hashArray.toString().split(',');
var hashtags = '';
for(var i = 0; i < hashStrings.length; i++) {
hashtags = hashStrings[i];
console.log(hashtags);
}
}
}
Check the .length of the array. If it's 0 then it contains no elements, in which case continue to the next loop iteration. EDIT per comments for the array we're testing, seems more likely you'll be testing data.data[x].tags.length:
success: function(data){
console.log(data);
for(x in data.data){
if (data.data[x].tags.length == 0) continue;
var hashArray = data.data[x].tags;
var hashStrings = hashArray.toString().split(',');
var hashtags = '';
for(var i = 0; i < hashStrings.length; i++) {
hashtags = hashStrings[i];
console.log(hashtags);
}
}
}

adding an array into an array at a particular position (based on key value) in javascript

I searched a lot, but I could not get a satisfactory answer on the net. In javascript, how do I add an array into another multidimensional array at a particular position based on a key value?
finalArray = []; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = [];
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp; // This gives an error
}
basically, I have
group = [ 'alpha' ,'beta', 'gamma' ]; //this array generated dynamically
my finalArray should be like,
finalArray['alpha'] = [ some records ];
finalArray['beta'] = [ some records ];
....
As far as I know, the way to add array into another array is to use .push() method, but that creates indices as 0, 1, 2... which is not desired. Please help me out
You have to use Object instead of Array. Make the following changes in the code
finalArray = {}; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = {};
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp;
}
console.log(finalArray); //to see the object key value structure
now you can reference the values in finalArray with group[i] name. Hope this helps
You have to define your finalArray variable as Object instead of and Array:
var finalArray = {}; //or better in your case finalMap
var group = [ 'alpha' ,'beta', 'gamma' ];
var finalArray = {}; //declare it object as you dont want 0,1 indexes
for (var index in group){
finalArray[group[index]] = "some records/arry of records"
}
console.log(finalArray);
DEMO

Return values in multiple arrays

My program is returning values in single array: ["addEcommerceItem", "hat", 29.99, "addEcommerceItem", "belt", 19.99];
I am trying to acheive (["addEcommerceItem", "hat", 29.99], ["addEcommerceItem", "belt", 19.99]);
Can anyone make suggestion
products = [
["hat", 29.99],
["belt", 19.99]
]
var testArray = new Array();
for(i in products){
testArray.push('addEcommerceItem');
testArray.push(products[i]);
}
var json = JSON.stringify(testArray);
<script type="text/javascript">
var _paq = _paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
_paq.push(json);
</script>
First of all, don't use for in enumerations on arrays.
Now, there are two ways of approaching the result you want. First, you can simply alter the existing array by prepending that item to every of them:
for (var i=0; i<products.length; i++)
products[i].unshift("addEcommerceItem");
console.log(JSON.stringify(products));
If that's not what you want, you would construct a new array rather:
var _paq = […]; // somewhere
for (var i=0; i<products.length; i++)
_paq.push(["addEcommerceItem"].concat(products[i]));
console.log(JSON.stringify(_paq));
Instead of the concat, you could of course use a second loop:
var _paq = […]; // somewhere
for (var i=0; i<products.length; i++) {
var product = products[i],
temp = [];
temp.push("addEcommerceItem";
for (var j=0; j<product.length; j++)
temp.push(product[j]);
_paq.push(temp); // push each array individually
}
console.log(JSON.stringify(_paq));
Just write what you want to happen: replace each sub-array with its elements preprended by "addEcommerceItem". You could use concat for that:
function prepend(item) { return ["addEcommerceItem"] . concat(item); }
Or, if you prefer,
function prepend(item) { item.unshift("addEcommerceItem"); return item; }
Then it's just
function transform(products) { return products . map(prepend); }
Sample usage:
>> products = [ ["hat", 29.99], ["belt", 19.99] ]
>> transform(products)
<< [ ["addEcommerceItem","hat",29.99], ["addEcommerceItem","belt",19.99] ]
To call _paq.push with each item in the resulting array as one argument, then
_paq.push.apply(_paq, transform(products))
In ES6:
var prepend = item => ["addEcommerceItem", ...item];
var transform = products => products . map(prepend);
_paq.push(...transform(products));
To achieve your desired output, I've modified the for-loop to splice in the additional value to the products array instead of pushing it to the testArray.
var testArray = new Array();
for (var i=0; i < products.length; i++){
products[i].splice(0,0,'addEcommerceItem');
testArray.push(products[i]);
}
A JS Bin demonstrating the results can be seen here.

Combining arrays to use in Google Sheets

I'm having some trouble combining arrays into one array and then flipping it with the code below. The goal is to set an array of values in one column of a spreadsheet. After the titleArray function, I would like to have an array spread across multiple columns on one row. Then, using a function I found in another Stack Overflow thread (Google Spreadsheet Script - How to Transpose / Rotate Multi-dimensional Array?), I want to flip the array so it is spread across multiple rows on one column. The current code is returning an array for each element in array1 all inside of another array. Then, the transposeArray function is combining values from each array, 1 with 1, 2 with 2, and so on. Can anyone spot what I'm doing wrong here?
var titleArray = function(){
var output = [];
for(i=0; i < array1.length; i++){
if(array1[i].length > 0){
var titles = ["",array1[i] + " Data"].concat(array2, array3, array4, array5, array6, array7);
output.push(titles);
}
}
return(output);
}
}
function transposeArray(array){
var result = [];
for (var col = 0; col < array[0].length; col++) { // Loop over array cols
result[col] = [];
for (var row = 0; row < array.length; row++) { // Loop over array rows
result[col][row] = array[row][col]; // Rotate
}
}
return result;
}
transposeArray(titleArray);
I was able to sit down with a programmer and he helped me through this. Essentially, I needed to use the concat method instead of the push method. I tried using concat early in this process but was using it in the first way demonstrated below instead of the second. I've included the full new code below as well.
output.concat(titles);
output = output.concat(titles);
var titleArray = function(){
var output = [];
for(i=0; i < array1.length; i++){
if(array1[i].length > 0){
var titles = ["",array1[i] + " Data"].concat(array2, array3, array4, array5, array6, array7);
ouput = output.concat(titles);
}
}
return(output);
}
}
function transposeArray(array){
var result = [];
for (var col = 0; col < array[0].length; col++) { // Loop over array cols
result[col] = [];
for (var row = 0; row < array.length; row++) { // Loop over array rows
result[col][row] = array[row][col]; // Rotate
}
}
return result;
}
transposeArray([titleArray]);

Categories