0

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

1
  • It has nothing to do with jQuery!!! Should be pure vanilla. Commented Oct 18, 2015 at 7:18

4 Answers 4

1

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]]

Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

0

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));

Comments

0

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>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.