3

Can someone show me the javascript I need to use to dynamically create a two dimensional Javascript Array like below?

desired array contents:

[["test1","test2","test3","test4","test5"],["test6","test7","test8","test9","test10"]]

current invalid output from alert(outterArray):

"test6","test7","test8","test9","test10","test6","test7","test8","test9","test10"

JavaScript code:

var outterArray = new Array();
var innerArray = new Array();
var outterCount=0;
$something.each(function () { 
   var innerCount = 0;//should reset the inner array and overwrite previous values?
   $something.somethingElse.each(function () {
        innerArray[innerCount] = $(this).text();
        innerCount++;
   }
   outterArray[outterCount] = innerArray;
   outterCount++;
}
alert(outterArray);
1
  • 1
    What does the input look like? Commented Mar 10, 2012 at 20:06

7 Answers 7

9

This is pretty cut and dry, just set up a nested loop:

var count = 1;
var twoDimensionalArray =[];

for (var i=0;i<2;i++)
{
  var data = [];
  for (var j=0;j<5;j++)
  {
    data.push("Test" + count);
    count++;
  }

  twoDimensionalArray.push(data);

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

Comments

7

It sounds like you want to map the array of text for each $something element into an outer jagged array. If so then try the following

var outterArray = [];
$something.each(function () { 
  var innerArray = [];
  $(this).somethingElse.each(function () {
     innerArray.push($(this).text());
  });
  outterArray.push(innerArray);
});

alert(outterArray);

Comments

2

A more flexible approach is to use raw objects, they are used in a similar way than dictionaries. Dynamically expendables and with more options to define the index (as string).

Here you have an example:

var myArray = {};
myArray[12]="banana";
myArray["superman"]=123;
myArray[13]={}; //here another dimension is created
myArray[13][55]="This is the second dimension";

Comments

1

You don't need to keep track of array lengths yourself; the runtime maintains the ".length" property for you. On top of that, there's the .push() method to add an element to the end of an array.

    // ...
    innerArray.push($(this).text());
  // ...
  outerArray.push(innerArray);

To make a new array, just use []:

innerArray = []; // new array for this row

Also "outer" has only one "t" :-)

Comments

1

[SEE IT IN ACTION ON JSFIDDLE] If that $something variable is a jQuery search, you can use .map() function like this:

var outterArray = [];

var outterArray = $('.something').map(function() {

    // find .somethingElse inside current element

    return [$(this).find('.somethingElse').map(function() {
        return $(this).text();
    }).get()]; // return an array of texts ['text1', 'text2','text3']

}).get(); // use .get() to get values only, as .map() normally returns jQuery wrapped array

// notice that this alert text1,text2,text3,text4,text5,text6 
alert(outterArray);​ 

// even when the array is two dimensional as you can do this: 
alert(outterArray[0]); 
alert(outterArray[1]);

HTML:

<div class="something">
    <span class="somethingElse">test1</span>
    <span class="somethingElse">test2</span>        
    <span class="somethingElse">test3</span>           
</div>
<div class="something">
    <span class="somethingElse">test4</span>
    <span class="somethingElse">test5</span>        
    <span class="somethingElse">test6</span>           
</div>

Here you can see it working in a jsFiddle with your expected result: http://jsfiddle.net/gPKKG/2/

Comments

0

I had a similar issue recently while working on a Google Spreadsheet and came up with an answer similar to BrianV's:

  // 1st nest to handle number of columns I'm formatting, 2nd nest to build 2d array   
  for (var i = 1; i <= 2; i++) {
    tmpRange = sheet.getRange(Row + 1, Col + i, numCells2Format); // pass/fail cells
    var d2Arr = [];
    for (var j = 0; j < numCells2Format; j++) {
      // 1st column of cells I'm formatting
      if ( 1 == i) {
        d2Arr[j] = ["center"];
      // 2nd column of cells I'm formatting
      } else if ( 2 == i ) {
        d2Arr[j] = ["left"];
      }
    }
    tmpRange.setHorizontalAlignments( d2Arr );   
  }

So, basically, I had to make the assignment d2Arr[index]=["some string"] in order to build the multidimensional array I was looking for. Since the number of cells I wanted to format can change from sheet to sheet, I wanted it generalized. The case I was working out required a 15-dimension array. Assigning a 1-D array to elements in a 1-D array ended up making the 15-D array I needed.

Comments

0

you can use Array.apply

        Array.apply(0, Array(ARRAY_SIZE)).map((row, rowIndex) => {
            return Array.apply(0, Array(ARRAY_SIZE)).map((column, columnIndex) => {
                return null;
            });
        });`

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.