Combining arrays to use in Google Sheets - javascript

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]);

Related

use loop function that calls itself instead of nesting loops to iterate through object of objects of arrays, but running into async issues

I have an object called foods that contains different categories of foods as objects. Each of those object "categories" contains an array of food items in their respective categories. I'm trying to iterate through this, creating meal objects that include one food item from each category. I then take the meal objects and store them in a container array called meals. My goal is to have the container array contain every possible combo of food items. Instead of writing a series of nested loops, I'm trying to write one loop function that calls itself, but I think some index values increment faster than the loop function is called, giving me issues.
The nested loops below work. Note that the meals container array contains over 100 meal objects upon completion:
var meals = [];
var meal = {};
var foods = {veggies:["asparagus","broccoli"],meat:["chicken","steak"],dessert:["pudding","ice cream"]};
var keys = Object.keys(foods);
for (var i = 0; i < foods[keys[0]].length; i++) {
meal[keys[0]] = foods[keys[0]][i];
for (var j = 0; j < foods[keys[1]].length; j++) {
meal[keys[1]] = foods[keys[1]][j];
for (var k = 0; k < foods[keys[2]].length; k++) {
meal[keys[2]] = foods[keys[2]][k];
meals.push(JSON.parse(JSON.stringify(meal)));
}
}
}
This (below) is how I'm trying to do it using a loop function, but it does not work, as the meals container array contains far fewer than the number of possible combos upon completion. Is there a way to make something like this work using a callback, promise or something else?
var meals = [];
var meal = {};
var foods = {veggies:["asparagus","broccoli"],meat:["chicken","steak"],dessert:["pudding","ice cream"]};
var keys = Object.keys(foods);
function runLoop(foodTypeNumber) {
for (var i = 0; i < foods[keys[foodTypeNumber]].length; i++) {
meal[keys[foodTypeNumber]] = foods[keys[foodTypeNumber]][i];
if (keys.length > foodTypeNumber + 1) {
runLoop(foodTypeNumber + 1);
} else {
meals.push(JSON.parse(JSON.stringify(meal)));
}
}
}
runLoop(0);
I've also noticed that when I take the code above and increment foodTypeNumber right before the if statement, I get a different result. Can someone help me understand what is going on here?
var meals = [];
var meal = {};
var foods = {veggies:["asparagus","broccoli"],meat:["chicken","steak"],dessert:["pudding","ice cream"]};
var keys = Object.keys(foods);
function runLoop(foodTypeNumber) {
for (var i = 0; i < foods[keys[foodTypeNumber]].length; i++) {
meal[keys[foodTypeNumber]] = foods[keys[foodTypeNumber]][i];
foodTypeNumber++;
if (keys.length > foodTypeNumber) {
runLoop(foodTypeNumber);
} else {
meals.push(JSON.parse(JSON.stringify(meal)));
}
}
}
runLoop(0);

js how to make 2d array matrix with for loop and continue counting numbers on next row

I'm trying to make my 2d matrix to have numbers which continue on the new row
var myMatrix = [];
var row = 5;
var colom = 3;
for (var i = 0; i < rows; i++) {
var toto = 1;
myMatrix[i] = [i];
for (var j = 0; j < colom; j++) {
myMatrix[i][j] = [i + j];
}
}
console.log(myMatrix);
I'm trying to make it print numbers like this:
123
456
789 and etc...
but without success:/
can someone help and also give a video or site with examples where i can learn more about that kind of stuff?
First, a look at what your code is doing:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [i];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = [i+j];
}
}
console.log(myMatrix);
You have a typo in your row/rows variable name. Ignoring that though...
Your myMatrix[i] line is creating an array at i, which is then being set to an array with a value of i. Just this creates a wonky mash-up , where each "row" gets an array with it's row number as the first value, something like this:
[[0], [1], [2], [3], [4]]
Your inner loop then adds a value to that array at the place and adds i+j together, but puts that inside of an array, which isn't what you want, so you get something like this:
[
[[0], [1], [2]], // i = 0
[[1], [2], [3]], // i = 1
[[2], [3], [4]], // i = 2
// ... etc
]
Also note that you are replacing that first [i] anyways, so don't set it like that, just make it an empty array [].
What you want is something like this:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = (i*columns)+j;
}
}
console.log(myMatrix);
There were three changes to your code:
Make the [i] and []. It doesn't hurt anything, but [i] also doesn't make sense.
Take the i+j part out of the array, you just want a value there.
When you add i, multiply it by columns so it doesn't reset every time: (i*columns)+j
This will give you a nice output, starting with 0. If you want it start at 1, just add one to your value:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = (i*columns)+j+1;
}
}
console.log(myMatrix);
Use i * columns + j ... and I have to add up to 30 chars for padding

Inserting items into a 2D array

I am working on solving an algorithm (do not want to explain my approach, as I am still trying to solve it on my own). However I am having difficulty with a particular part.
function smallestCommons(arr)
{
var rangeArray = [];
var outterArray = [];
var testArray = [];
arr = arr.sort(function(a,b){return a>b});
for(var i=arr[0];i<=arr[1];i++)
{
rangeArray.push(i);
}
for(var j=0;j<rangeArray.length;j++)
{
for(var k=1;k<=100;k++)
{
if(k%rangeArray[j] === 0)
{
outterArray.push([k]);
}
}
}
console.log(outterArray);
}
smallestCommons([1,5]);
The second part of the code I am looping through the items in rangeArray [1,2,3,4,5] and trying to insert all the multiples (from 1 to 100) of EACH index into a DIFFERENT array. But my code currently is pushing EACH individual number which is a multiple into its own array per each digit. I need it to push all the multiples of each index of rangeArray into outer array. So that I end up with a 2D array of all the multiples of rangeArray in different array for every iteration of j.
So for example instead of ending up with
outerArray == [[1],[2],[3]...]
I would end up with all the multiples of 1 (up to 100) into one array and then all the multiples of 2 into another array and so on and so forth so it looks like this.
outerArray == [[1,2,3,4...] [2,4,6,8...] [3,6,9,12...]]
Its very hard to explain, hopefully I have been clear. Thanks.
It's quite impossible to understand your question, but wisely you've described the output you're trying to generate...
Turns out, that's quite simple:
let arr = [];
for(let i = 1; i <= 100; i++) {
let innerArr = [];
for(let j = i; j <= 100; j += i) {
innerArr.push(j);
}
arr.push(innerArr);
}
console.log(arr);
how many elements should be in each multiple array? I guessed 100 but you can adjust that accordingly...
function smallestCommons(arr)
{
var rangeArray = [];
var outterArray = [];
var testArray = [];
arr = arr.sort(function(a,b){return a>b});
for(var i=arr[0];i<=arr[1];i++)
{
rangeArray.push(i);
}
for(var j=0;j<rangeArray.length;j++)
{
for(var k=1;k<=100;k++)
{
if(k%rangeArray[j] === 0)
{
var multipleArray = [];
for(var z=1;z<100;z++) {
multipleArray.push(z*k);
}
outterArray.push(multipleArray);
}
}
}
console.log(outterArray);
}
smallestCommons([1,5]);

Create Nested Empty Array Using For Loop Javascript

I'm trying to make a nested array with parameters that accepts 2 numbers as arguments that will be used to create the dimensions of a board.
In the following code, I would expect a 5X5 nested array to be printed, but instead am getting a 5x15 nested array.
function NestedArray(x,y) {
rows = [];
cells = [];
board = [];
for (var i = 0; i < x; i++) {
for (var j = i; j < y; j++) {
rows.push(cells);
}
board.push(rows);
}
console.log(board);
}
NestedArray(5,5);
Please forgive any formatting errors, I'm new to JS.
In the first loop you need to create row and push it to the board. In the second loop you need to create cell and push it to the current row:
function NestedArray(x,y) {
board = [];
for (var i = 0; i < x; i++) {
var arr = []; // create row
board.push(arr);
for (var j = 0; j < y; j++) {
arr.push([]); // create and push cell to row
}
}
console.log(board);
}
NestedArray(5,5);

Multiply each column of 2d array and return array

New to JS here. How can I use math.js or vanilla js to return an array where a 2d array is multiplied by each column. The size of the 2 arrays will always be the same.
[[2,2],
[2,4]]
results is
[4,8]
I have tried:
adjustedrating = [[2,2],[2,4]]
var w = adjustedrating.length;
for (var i = 0, len = adjustedrating[0].length; i < len; i++) {
var multiple = adjustedrating[0][i];
for (var j = 0; j < w; j++) {
multiple *= adjustedrating[j][i];
}
both.push(multiple);
};
What you can do is loop through the outer array, and store the results of the multiplication as you go. For instance:
// The two dimensional array
var twoDimArray = [[2,2],
[2,4]];
// We'll say this is where your results will go. It will be the same length
// as one of your inner arrays, and all values will start at 1
var results = [1,1];
// Loop through the 2D Array
for( var outerIndex = 0; outerIndex < twoDimArray.length; outerIndex++){
// Loop through the currently selected inner array
for( var innerIndex = 0; innerIndex < twoDimArray[outerIndex].length; innerIndex++){
// Multiply appropriate result by the appropriate value
results[innerIndex] *= twoDimArray[outerIndex][innerIndex];
}
}
// Simply displays the results somewhere
document.getElementById('results').innerHTML = results;
<div id="results"></div>

Categories