3

Possible Duplicate:
How to create a two dimensional array in JavaScript?

I want to push elements to 2D array,

My code is,

        var results = [];
        var resultstemp = [];
        function bindlinks(aamt,id1) {
        resultstemp=results;        
            imagesArray.push($("#image1").mapster("get"));

            if(results.length==0)
            {
            results.push([id1]);    
            }
            else
            {
               var ck=0;
               var lng=results.length;
                for (var i = 0; i < lng; i++) {

                  if(results[i]==id1)
                  {

                    ck=1;
                     results = jQuery.grep(results, function(value) {
                        return value != id1;
                      });

                  }                                     
                }                   
                if(ck==0)
                {
                results.push(id1);                  
                }                   
            }

I want to push id as well as aamt to array. Here i am pushing only id to array. I am not sure about how to add aamt to second position in 2D array.

Help me please,

Thank you

Community
  • 1
  • 1
Erma Isabel
  • 2,167
  • 8
  • 34
  • 64

2 Answers2

6

Change the declaration as follows:

var results = new Array();

and change the push as follows:

results.push([id1,aamt]);

Hope it would help

Xmindz
  • 1,282
  • 13
  • 34
  • This isnt working since push takes only one element. When i tried this code the values id1 and aamt is pushed to same position in 1D array separated by comma – Erma Isabel Aug 24 '12 at 05:58
  • That is how a 2D array will look like. :) Eg: `[[1,2],[3,4],[5,6]]` – Xmindz Aug 25 '12 at 09:10
0

The logic behind the method to push two separate values in the same array evenly is something like this:

var array = [];
function push(id1, aamt) {
    for (var i= 0; i < 10; i++) {
        if (i%2 == 0) {
            array.push(id1);
        }
        else {
            array.push(aamt);
        }
    }    
}

push(10, 12);
console.log(array); // 10, 12, 10, 12.....

Take note i abstracted the code quite a bit, because for me was not too obvious what the code should have to do, but the principle is simple: use the modulo (%) operator to test if the value is odd or even. If odd add the first value if even add the second value.

Hope it helps.

Endre Simo
  • 11,330
  • 2
  • 40
  • 49