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

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

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

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

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.

Efficient way to turn a string to a 2d array in Javascript

I need to check from a string, if a given fruit has the correct amount at a given date. I am turning the string into a 2d array and iterating over the columns.This code works, but I want to know : is there a better way to do it? I feel like this could be done avoiding 4 for loops.
function verifyFruit(name, date, currentValue) {...}
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var rows = data.split('\n');
var colCount = rows[0].split(',').length;
var arr = [];
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < colCount; j++) {
var temp = rows[i].split(',');
if (!arr[i]) arr[i] = []
arr[i][j] = temp[j];
}
}
for (var i = 1; i < colCount; i++) {
for (var j = 1; j < rows.length; j++) {
verifyFruit(arr[0][i], arr[j][0], arr[j][i]);
}
}
This would be a good candidate for Array.prototype.map
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var parsedData = data.split("\n").map(function(row){return row.split(",");})
What map does is iterate over an array and applies a projection function on each element returning a new array as the result.
You can visualize what is happening like this:
function projection(csv){ return csv.split(",");}
var mappedArray = [projection("Date,Apple,Pear"),projection("2015/04/05,2,3"),projection("2015/04/06,8,6")];

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