Javascript Array 2 Dimension For Loop
Solution 1:
There are some things you can do with your code for optimization. First you have to initialize your loop correctly. then inside the loop, it is better to assign the value statically rather checking it every time for only one implementation. This should optimize your code. The old location posting could make the following code more optimized.
var newLoc = [];
if(locations.length > 0){
for(var j = 0; j < 1; ++j) {
newLoc[j] = [ ];
newLoc[j][0] = locations[0][1];
newLoc[j][1] = locations[0][2];
}
}
for (var i = 1, i < locations.length; i++){
if(locations[i][8] == locations[i-1][8]){
newLoc[i-1][0] = (locations[i][1] + locations[i-1][1])/2;
newLoc[i-1][1] = (locations[i][2] + locations[i-2][1])/2;
}
else{
newLoc[i][0] = locations[i][1];
newLoc[i][1] = locations[i][2];
}
}
Solution 2:
I think the issue is that newLoc is always a 1 dimentionnal array and you declare 'index' in your for loop but use 'i' in the body
var newLoc = [];
// loop with for (var i = 0; i < locations.length; i++){
//Create the second dimention
newLoc[i] = [];
if(i == 0) {
...
Solution 3:
One thing I noticed, in your for
loop, you have written
for (index = 0, i < locations.length; i++)
instead of
for (index = 0; i < locations.length; i++)
Note the ;
So, in all the loop should be
for (index = 0; i < locations.length; i++){
if(i == 0) {
newLoc[i][0] = locations[i][1];
newLoc[i][1] = locations[i][2];
}
else {
if(locations[i][8] == locations[i-1][8]){
newLoc[i-1][0] = (locations[i][1] + locations[i-1][1])/2;
newLoc[i-1][1] = (locations[i][2] + locations[i-2][1])/2;
}
else{
newLoc[i][0] = locations[i][1];
newLoc[i][1] = locations[i][2];
}
}
}
Solution 4:
You are initializing a one-dimensional array, so, when you iterate over the loop, your javascript code will probably you break.
Try to initialize using this way:
var newLoc = newArray(locations.length).fill(locations.length);
Array Doc: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array
Post a Comment for "Javascript Array 2 Dimension For Loop"