Create Nested Empty Array Using For Loop Javascript - 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);

Related

Array is overwriting previous object

I am creating an object with my XML data and pushing into the array. But when it coming out from the method I can see all the array value is copy of first one. Can anyone help me.
Here is my code :
var obj = {};
for(var i = 1; i < myData.length; i++) {
var myDAtt = myData[i].getElementsByTagName('D');
for(var j = 0; j < myDAtt.length; j++){
obj[myDAtt[j].getAttribute('dataIndex')] = myDAtt[j].getAttribute('V')
}
me.Rec.push(obj);
}
You need to create a new object in the top level for loop. In your case you have only one variable, for which you are adding properties and push into the array it's reference. So at the end you have one big object and pushed the reference of it into the array for many times.
for(var i = 1; i < myData.length; i++) {
var obj = {};
var myDAtt = myData[i].getElementsByTagName('D');
for(var j = 0; j < myDAtt.length; j++) {
obj[myDAtt[j].getAttribute('dataIndex')] = myDAtt[j].getAttribute('V')
}
me.Rec.push(obj);
}

Edit specific element in JavaScript 2D array and not the column

When manually creating a 2D array and editing a specific element I get the desired results. If I create it with a for loop and edit one element in the array, it changes the whole array in each row, in turn editing the whole column.
Is there a better way to create 2D arrays with a for loop to avoid this behavior?
var grid = [1,2,3];
var gridRows = ["O","O","O"];
for (var i = 0; i < grid.length; i++) {
for(var j = 0; j < grid.length; j++) {
grid[i] = gridRows;
}
}
Image of the for loops output
//--------------------
//The manually created 2D Array
manualGrid = [["O","O","O"],["O","O","O"],["O","O","O"]];
Image of the manual methods output in console
Arrays are objects in javascript which are passed by reference . To avoid this just change your code to :
var grid = [1,2,3];
var gridRows = ["O","O","O"];
for (var i = 0; i < grid.length; i++) {
for(var j = 0; j < grid.length; j++) {
grid[i] = JSON.parse(JSON.stringify(gridRows));
}
}

Javascript Array function has bug I cannot see

I am writing a function which should create a 2 dimensional array pre-populated with zeros. My output looks correct, but apparently there is a bug in it that I am not seeing. Does anybody know what it is? I don't see it.
function createMatrix(size) {
var defValue = 0;
var row = [];
var matrix = [];
for (var i = 0; i < size; i++) {
row.push(defValue);
}
for (var i = 0; i < size; i++) {
matrix.push(row);
}
return matrix;
}
You're pushing the same row into your array matrix every time. These all point to the same array, since they are passed by reference.
You should make a new array for each row instead:
function createMatrix(size){
var defValue = 0;
var matrix = [];
for (var i = 0; i < size; i++) {
var row = [];
for (var j = 0; j < size; j++) {
row.push(defValue);
}
matrix.push(row);
}
return matrix;
}
The problem lies in the second loop;
If you stop and trace your code, you can see that you are only creating one "row" array whereas you most likely want to make size amount of rows.
Your code should probably look like this
var matrix = [];
for(var i = 0; i < size; i++) {
//temp row to append to array
var row = [];
//fill row array with 0s
for (var j = 0; j < size; j++) {
row.push(0);
}
//append row to the matrix
matrix.push(row);
}
return matrix
This way you are pushing a completed row at the end of each iteration.

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

Assigning objects in 2-D array

Let's say I got an object as follows:
function node(xVal, yVal, nodeType) {
this.xVal = xVal; // x-coordinate of node
this.yVal = yVal; // y-coordinate of node
this.nodeType = nodeType; // node type - outside the scope of this question
}
In an attempt to create a series of nodes on a x-by-y virtual plane, I specified a two-dimensional array as follows:
var ROWS = 3; // number of rows in the array
var COLS = 10; // number of columns in the array
var Nodes = new Array(ROWS);
for (var i=0; i < ROWS; i++) {
for (var j=0; j < COLS; j++) {
Nodes[i][j] = new node(0, 0, "Type A");
}
}
I was expecting the above embedded for-loop would allow me to initialize the 3x10 array, each with 'node' object but something appears to be causing an error. Any thoughts as to 1) what might be causing the error, and 2) how to improve the logic will be greatly appreciated!
It is causing an error because you did not initialize a new array on the first dimension. Try putting Nodes[i] = []; before your second loop.
Also, you don't have to initialize an Array like that. You can just du var Nodes = [];
You should define the inner array as well.
for (var i=0; i < ROWS; i++) {
Nodes[i] = new Array(COLS);
for (var j=0; j < COLS; j++) {
Nodes[i][j] = new node(0, 0, "Type A");
}
}

Categories