Reputation: 409
Hi I am trying to add some values to a multidimensional array using a for loop. This is what I have created so far:
var test1 = [];
var test2 = [];
for (var i = 0; i < top10.length; i++)
{
test1[i] = i;
test1[i][0] = top10[i][0];
test1[i][1] = top10[i][1];
}
This is just returning an empty array. top10 is a multidimensional array which contains:
It can contain more data that's why I need a for loop. I am trying to create 2 multidimensional arrays "test1" and "test2" one will contain "Hinckley Train Station" and "4754" the other will contain "Hinckley Train Station" and "2274".
I can have multiple venues not just "Hinckley Train Station" "4754" "2274" I could also have "London City" "5000" "1000". This is why it is a for loop.
Upvotes: 2
Views: 8527
Reputation: 386560
You could push a new array to the wanted parts
var top10 = [
["Hinckley Train Station", "4754", "2274"],
["London City", "5000", "1000"]
],
test1 = [],
test2 = [],
i;
for (i = 0; i < top10.length; i++) {
test1.push([top10[i][0], top10[i][1]]);
test2.push([top10[i][0], top10[i][2]]);
}
console.log(test1);
console.log(test2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2
Reputation: 92274
In this line
test1[i] = i;
You are assigning an integer to be the first element of the outer array. You don't have a 2d array, you have an array of integers
In the following lines:
test1[i][0] = top10[i][0];
test1[i][1] = top10[i][1];
You are assigning properties to an integer, which means they are being boxed but the boxed value is thrown away.
It's hard to tell what you are trying to do, but the following is probably closer. You need to create a new inner array each time through the loop.
for (var i = 0; i < top10.length; i++)
{
test1[i] = [];
test1[i][0] = top10[i][0];
test1[i][1] = top10[i][1];
// Maybe do something similar with test2
}
Upvotes: 1