htoniv
htoniv

Reputation: 1668

create two dimension array and push values in javascript

Here i am creating two dimensional array and push values into it. In this code i create empty array using for loop and again i am using forloop to push the values into an array.My question I need to create an array and push the values in an array with one time for loop.

var arr = [];
for (var tot=0;tot<4;tot++) {//creating empty arrays
    arr.push([]);
}
for (var tot=0;tot<4;tot++) {//pushing values into an array
    for (var i=0;i<3;i++) {
        arr[tot].push(i);
    }
}
console.log(JSON.stringify(arr));//[[0,1,2],[0,1,2],[0,1,2],[0,1,2]]

answer either in javascript or jquery

Upvotes: 0

Views: 90

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386604

Just use function method Function.prototype.apply() with an object which specifies the length and array method Array.prototype.map() for filling with another array and the values.

var n = 3,
    array = Array.apply(Array, { length: n }).map(function () {
        return Array.apply(Array, { length: n }).map(function (_, i) {
            return i;
        });
    });

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

Upvotes: 0

guest271314
guest271314

Reputation: 1

My question I need to create an array and push the values in an array with one time for loop

If expected result is console.log(JSON.stringify(arr));//[[0,1,2],[0,1,2],[0,1,2],[0,1,2]] , could push initial array item to same array ?

If arr.length is 0 push tot , tot + 1 , tot + 2 to arr , else push arr[0] to arr

var arr = [];
for (var tot = 0; tot < 4; tot++) {
    if (!arr.length) arr.push([tot, tot + 1, tot + 2])
    else arr.push(arr[0])
}
console.log(JSON.stringify(arr));

Upvotes: 0

MoLow
MoLow

Reputation: 3084

try this ,for a O(n) loop:

var arr = [],dimentions = [3,4];
for (var i = 0; i< dimentions[0] * dimentions[1];i++) {
    var x = Math.floor(i/dimentions[0]), y = i%dimentions[0];
    arr[x] = arr[x] || [];
    arr[x].push(y);
}
console.log(JSON.stringify(arr));//[[0,1,2],[0,1,2],[0,1,2],[0,1,2]]

if you ok with an O(n^2) nested loop:

var arr = [];
for (var i = 0; i < 4; i++) {//pushing values into an array
    arr[i] = arr[i] || [];
    for (var j = 0; j < 3;j++) {
        arr[i].push(j);
    }
}
console.log(JSON.stringify(arr));//[[0,1,2],[0,1,2],[0,1,2],[0,1,2]]

Upvotes: 1

user2314737
user2314737

Reputation: 29317

Try with:

var arr = [];
for (var tot = 0; tot < 4; tot++) { //creating empty arrays
  arr.push([]);
  for (var i = 0; i < 3; i++) {
    arr[tot].push(i);
  }
}
console.log(JSON.stringify(arr));

Upvotes: 0

Related Questions