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

7
  • 1
    is var results = [][]; even a valid syntax? Commented Aug 24, 2012 at 4:53
  • no..that is not valid...my mistake Commented Aug 24, 2012 at 4:54
  • 1
    I'm somewhat confused as to what you want to do... Can you reword the question? Commented Aug 24, 2012 at 5:00
  • 1
    Can you please explain your end goal instead of just asking to fix the code? Commented Aug 24, 2012 at 5:03
  • 1
    So you want to push aamt and id1 evenly into a 2d array? Commented Aug 24, 2012 at 5:03

2 Answers 2

6

Change the declaration as follows:

var results = new Array();

and change the push as follows:

results.push([id1,aamt]);

Hope it would help

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

2 Comments

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
That is how a 2D array will look like. :) Eg: [[1,2],[3,4],[5,6]]
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.