Why can't I copy a part of my array in Node? - javascript

I'm trying to set up an array in which a part is repeated twice. It consists of three articles (in articleArray[0] through articleArray[2]) and for each there's a list of every word in the article (for instance articleArray[1][1] lists each word in that article). I want to clone that last part to articleArray[1][2], but for some reason it won't work? I'm using a for-loop
for (var x=0; x < articleCount; x++) {
for (var y=0; y < articleArray[x][1].length; y++) {
articleArray[x][2] = [];
articleArray[x][2][y] = articleArray[x][1][y];
}
}
After running that, each value in articleArray[1][2] is empty except the last one, for some reason. Why is it not copying my values?

You're repeatedly overwriting articleArray[x][2] with an empty array. You will need to move the line
articleArray[x][2] = [];
one level up, outside of the inner loop:
for (var x=0; x < articleCount; x++) {
articleArray[x][2] = [];
for (var y=0; y < articleArray[x][1].length; y++) {
articleArray[x][2][y] = articleArray[x][1][y];
}
}
Notice that this can be simplified using slice to clone the array:
for (var x=0; x < articleCount; x++) {
articleArray[x][2] = articleArray[x][1].slice();
}

how about this version?
articleArray.forEach(arr => {
arr[2] = arr[1].slice();
});

Related

Getting an array index from 2 values

I wasn't sure how to properly word the title.
I have 2 indexes from a 2D array (x and y) and need to multiply them together to get the index for a second array (1D), however it's not that simple 'cause if x or y equals zero, it'll return zero regardless of the other value.
I could get around this using nested loops shown below:
int count = 0;
for( int i = 0; i < x; i++ )
{
for( int j = 0; j < y; j++ )
{
count++;
}
}
//count now equals desired value
...but that seems awfully impractical.
To me this seems like something that should be incredibly simple and I've put off asking until now, thinking that might be the case.
Let’s use the following data to create an example:
var array_2d = [[0,1,2],[3,4,5]];
var array_1d = [0, 1, 2, 3, 4, 5];
If all of your sub arrays have the same size, you can simply multiply your i index by your sub array’s length, in order to find the corresponding “row” of your 1 dimensional array. Then you can simply add the “column” index of your array.
But this would only work if you are working with width-fixed matrixes.
var sub_dimensional_array_length = 3;
for (var i = 0; i < array_2d.length; i++) {
for (var j = 0; j < array_2d[i].length; j++) {
var array_1d_index = (sub_dimensional_array_length * i) + j;
console.log(array_2d[i][j], array_1d[array_1d_index]);
}
}

For loop lasts infinitely javascript

I have a problem in my code:
var row = ["1","2","3","4","5"];
var column = ["1","2","3","4","5"];
var arrayLength = row.length;
var arrayLength2 = column.length;
for (var i = 0; i < arrayLength; i++) {
for (var e = 0; e < arrayLength2; e++) {
var samples = document.querySelectorAll('[data-row-id="'+row[i]+'"][data-column-id="'+column[e]+'"]');
for(var i = 0; i < samples.length; i++) {
var sample = samples[i];
sample.setAttribute('data-sample-id', row);
console.log("Colore cambiato");
}
}
}
When i run it, the cycle lasts infinitely and the console.log is called up a lots of times
Where is the error? Thanks!
The problem is that your inner-most loop uses the same i looping variable as your outer most loop and it's constantly changing i so that the outer loop never finishes.
Change the variable on your inner loop to a different identifier that you aren't already using in the same scope.
Youre using same loop i twice nested so it runs infinitely coz it always resets i in inner loop
use something else instead like k
for(var k = 0; k < samples.length; k++) {
var sample = samples[k];
sample.setAttribute('data-sample-id', row);
console.log("Colore cambiato");
}

first loop stops when the second starts

I want to use a for loop in another for loop to get the content of an xml file.
The problem is that when the second loop starts the first one stops.
javascript code:
var x = xmlDoc.getElementsByTagName('usr');
for (i=0; i <= x.length; i++) {
var y = x[i].childNodes;
for(n=0; n <= y.length; n++) {
var z = y[n].childNodes[0];
document.write(z.nodeValue);
}
}
xml code:
<usr><age>30</age><location>uk</location></usr>
<usr><age>25</age><location>usa</location></usr>
And the output is:
30uk
It should be 30uk25usa
In both of your loops, you will iterate one too many times.
i=0; i<=x.length should be i = 0; i < x.length and same for the inner loop.
Iterating one too many times generates an error, which breaks the execution
Try storing the total result that you want outside of the first loop, and then use document.write() after the outer loop completes:
var x = xmlDoc.getElementsByTagName('usr');
var zTotal = '';
for (i=0; i < x.length; i++) {
var y = x[i].childNodes;
for(n=0; n < y.length; n++) {
var z = y[n].childNodes[0];
zTotal += z.nodeValue;
}
}
document.write(zTotal);

Javascript: confused about how nested for loops work

Why do nested for loops work in the way that they do in the following example:
var times = [
["04/11/10", "86kg"],
["05/12/11", "90kg"],
["06/12/11", "89kg"]
];
for (var i = 0; i < times.length; i++) {
var newTimes = [];
for(var x = 0; x < times[i].length; x++) {
newTimes.push(times[i][x]);
console.log(newTimes);
}
}
In this example I would have thought console.log would give me the following output:
["04/11/10"]
["86kg"]
["05/12/11"]
["90kg"]
["06/12/11"]
["89kg"]
However, I actually get this:
["04/11/10"]
["04/11/10", "86kg"]
["05/12/11"]
["05/12/11", "90kg"]
["06/12/11"]
["06/12/11", "89kg"]
Is anyone able to help me understand this?
EDIT:
Thanks for all your responses!
You are redefining newTimes on every single loop and you are outputting to the console on each column push.
var times = [
["04/11/10", "86kg"],
["05/12/11", "90kg"],
["06/12/11", "89kg"]
];
var newTimes = [];
for (var i = 0; i < times.length; i++) {
for(var x = 0; x < times[i].length; x++) {
newTimes.push(times[i][x]);
}
}
console.log(newTimes);
Returns: ["04/11/10", "86kg", "05/12/11", "90kg", "06/12/11", "89kg"]
http://jsfiddle.net/niklasvh/SuEdt/
// remember that the increment of the counter variable
// is always executed after each run of a loop
for (var i = 0; i < n; i++) {
// some statement(s) to do something..
// initializes child-loop counter in the first run of the parent-loop
// resets child-loop counter in all following runs of the parent-loop
// while i is greater than 0 and lower than n
for (var j = 0; j < p; j++) {
// some statement(s) to do something..
// initializes grandchild-loop counter in the first run of the child-loop
// resets grandchild-loop counter in all following runs of the child-loop
// while j is greater than 0 and lower than p
for (var k = 0; k < q; k++) {
// some statement(s) to do something..
// or add more internal loop-nestings if you like..
}
}
}
// if the counter variables of the descendent-loops were set before the loop-nesting,
// the inner loops would only run once, because the counter would keep the value
// of the abortion condition after the loop is finished
Do this:
var newTimes = [];
for (var i = 0; i < times.length; i++) {
for(var x = 0; x < times[i].length; x++) {
newTimes.push(times[i][x]);
console.log(newTimes);
}
}
You are re-initializing newTimes each time through the loop.
You output would be appropriate if the log statement would read
console.log(times[i][x]);
Instead you output your complete new list newTimes which is initialized outside the inner loop and grows with each inner loop iteration.
The problem is in the second round of the inner loop, where it pushes the second element into newTimes. Anyway I don't understand the reason of inner loop. You can write much simpler:
var times = [
["04/11/10", "86kg"],
["05/12/11", "90kg"],
["06/12/11", "89kg"]
];
for (var i = 0; i < times.length; i++) {
console.log(time[i][0]);
console.log(time[i][1]);
}

Every element in an array being incremented simultaneously when only one should be

I am using the following code to increment the elements in a 2d array surrounding a given element.
EmptyCell = {number: 0}; //This has several parts in the actual code.
list = new Array();
function init(w,h){
for (var x = 0; x <= w; x++){
list[x] = new Array();
for (var y = 0 ; y <= h; y++){
list[x][y] = EmptyCell;
}
}
}
function map(func,x,y){
var xoff = [1,1,1,0,0,-1,-1,-1];
var yoff = [1,0,-1,1,-1,1,0,-1];
for (var atIndex = 0; atIndex < 8; atIndex++){
func(x+xoff[atIndex],y+yoff[atIndex]);
}
}
And then I run it like this:
init(10,10);
map(function(x,y){
if (list[x] != null && list[x][y] != null){
list[x][y].number++;
}
},0,0);
Each time list[x][y].number++ is run, every element in the entire array is incremented.
Could somebody explain why this is happening?
EmptyCell is an object, so all the elements reference the same object. If you want to use separate objects for each element, create a new instance each time.

Categories