0

I have multidimentional array functions which are obtaining the values from database sqlite .

var myarray = [];

The array values will be like the below :

myarray[0][0] = "ABC";
myarray[0][1] = "abc";
...
...
...
myarray[3][1] = "GHI";

I need to store array values like this in a variable :

var  md2 = [[myArray[0][0], myArray[0][1]],
    [myArray[1][0], myArray[1][1]],
    [myArray[2][0], myArray[2][1]],
    [myArray[3][0], myArray[3][1]]];

How do i declare the above array values dynamically?

I tried the below :

for(var t =0; t<md2.length; t++){

var g = 0;

md2 = [myarray[t][g],myarray[t][g+1]];

}

This above is not working .

My expected Result is this using for loop:

var  md2 = [[myArray[0][0], myArray[0][1]],
        [myArray[1][0], myArray[1][1]],
        [myArray[2][0], myArray[2][1]],
        [myArray[3][0], myArray[3][1]]];

How can i do that using for loop or other. Suggestions are highly appreciable.

9
  • What exactly are you trying to do? Just make copy of first array? Commented Feb 3, 2016 at 5:25
  • just decalare a new array and use push method Commented Feb 3, 2016 at 5:26
  • @charlietfl . I m just need to store [myArray[0][0] ...... values dynamically using loop conditions. because the myArray length may differ from databale Commented Feb 3, 2016 at 5:31
  • @kpsingh can u tell me how to do that dynamically Commented Feb 3, 2016 at 5:33
  • Your expected output is bit difficult to understand. Can you simply it further? Commented Feb 3, 2016 at 5:35

4 Answers 4

2

You can use the code below. Check demo - Fiddle

var md2 = [];
for (var t=0; t < myarray.length; t = t+2){
   if (myarray[t] && myarray[t+1]) {
         md2.push( [ myarray[t], myarray[t+1] ] );
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks frd , this not working for me but tq for spending time :) ..... But working in JQfiddle
1

Both of these approaches will give you a copy of myarray which is all you are doing in your code as it is now

var md2 = [].concat(myarray);
// OR
var md2 = myarray.slice();

Both are non destructive and will leave myarray untouched

Comments

0

A two-dimensional array is created simply by building on a "normal" array.

 var aa = new Array(3)
 for(var i=0; i<3;i++) {
    aa[i]=new Array(3);
    for(var j=0; j<3;j++) {
       aa[i][j] = j;
    }
  }
  console.log(aa);

 Output: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Hope it helps.

Comments

0

you can use this code for store value from multidimensional to single

var md2 = [];
var cnt = 0;
for(var i=0;i<myArray.length;i++){
md2[i] = myArray[i];
}

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.