I am trying to push the values [100,1000,10000,200,2000,20000,300,3000,30000] inside the multidimensional array in Javascript.
Multidimensional array should look like below
[[100,1000,10000],[200,2000,20000],[300,3000,30000]]
I am using the below code
var j = 0;
var x = 0;
var z = 0;
var f = new Array();
var rows = [100, 1000, 10000, 200, 2000, 20000, 300, 3000, 30000];
for (var i = 1; i <= rows.length; i++) {
if (j < i) {
f[x] = new Array();
var arrval = parseInt(rows[j]);
f[x][z] = arrval;
z++;
if (i % 3 == 0) {
x++;
z = 0;
}
j++;
}
}
But the push into multidimensional array push seems to be not working. The final output is looking like [[,,10000],[,,20000],[,,30000]]
Could you please help?
Thanks in advance
5 Answers 5
Try this:
var rows = [100, 1000, 10000, 200, 2000, 20000, 300, 3000, 30000];
var newarr = new Array();
/*for(var i =0; i< rows.length; i++){
newarr.push(rows.splice(0,3));
}
console.log(newarr);*/
while(rows.length){
newarr.push(rows.splice(0,3));
}
You can even make a function that would receive the number of columns as parameters.
function(orArr, nArr, cols){
for(var i =0; i< orArr.length; i++){
nArr.push(rows.splice(0,cols));
}
Update
: You should actually use slice() instead of splice() . as your original array would be modified if you are using splice(); In that case your code would be:var newarr = new Array();
for(var i =0; i< rows.length; i++){
newarr.push(rows.slice(0,3));
}
console.log(newarr);
Comments
You are clearing f[x] each iteration!
Here is a fix :)
var rows = [100,1000,10000,200,2000,20000,300,3000,30000];
var x=0; var z=0; var f = new Array();
for (var i=1;i<=rows.length;i++) {
if(!f[x]){
f[x]=new Array();
};
f[x][z]=parseInt(rows[i-1]);
z++;
if(i%3==0)
{
x++;
z = 0;
}
}
Comments
Here's another way to do it with a single loop http://jsfiddle.net/rene3/
var f = [];
var rows = [100, 1000, 10000, 200, 2000, 20000, 300, 3000, 30000];
for (var i = 0, len = rows.length; i < len ; i++) {
if( !(i%3) ){
f.push([]);
}
f[Math.floor(i/3)].push(rows[i])
}
Comments
var f = [];
f.push([[100,1000,10000],[200,2000,20000],[300,3000,30000]]);
if there should be a dynamic loop, you could try:
var f = [];
var MyVal = n; // n = any value you like
var Val100, Val1000, Val10000;
for (var i=1; i<MyVal+1; i++){
Val100 = i*100;
Val1000 = i*1000;
Val10000 = i*10000;
f.push([Val100,Val1000,Val10000]);
}
Comments
var f = new Array(),
x = 0,
rows = [100, 1000, 10000, 200, 2000, 20000, 300, 3000, 30000];
for (var i = 0; i < rows.length; i++) {
var a;
if (i % 3 == 0) {
f[x] = new Array();
a = f[x];
x++;
}
a.push(rows[i]);
}