Andrew
Andrew

Reputation: 505

How do I create a Multidimensional Array in Javascript?

My goal is to iterate over a table with an ID of ajaxResponse1 and store each COLUMN'S values in a separate array. Each of the entries in valuesArr will be a column containing an array of individual values.

I tried using new Array instead of new Object, but I still don't seem to be getting any output alerted to my screen. Should I be using some combination of .push to get each new column value into the appropriate array? Hope that's clear. Any ideas? Thanks!

var valuesArr = new Object();

$('#ajaxResponse1 tr').each( function() {
    var colNum = 0;
    $('th, td', this).each( function() {
        valuesArr[colNum] = valuesArr[colNum].push( $(this).html() );   
        colNum++;
    });
});

alert(JSON.stringify(valuesArr));

Upvotes: -1

Views: 318

Answers (4)

Multidimensional array = embeded arrays. See if this tiny model can help. thanks.

   "use strict";
   const arr = [
       ["D1","D2","D3"],
       [
           ["T11","T12","T13"],
           ["T21","T22","T23"]
       ]
   ];

   for(let k=0;k<arr[0].length;k++)
      console.log(arr[0][k]);
      // D1
      // D2
      // D3

   for(let k=0;k<arr[1].length;k++)
      console.log(arr[1][k]);
      // Array(3) [ "T11", "T12", "T13" ]
      // Array(3) [ "T21", "T22", "T23" ]

   for(let k=0;k<arr[1].length;k++)
      console.log(arr[1][0][k]);
      // T11
      // T12

   for(let k=0;k<arr[1].length;k++)
      console.log(arr[1][1][k]);
      // T21
      // T22

Upvotes: 0

Alnitak
Alnitak

Reputation: 339816

You can't push something onto an array until that array actually exists.

So in each iteration of your inner loop, if the initial array doesn't exist you have to create it:

var valuesArr = [];

$('#ajaxResponse1 tr').each( function() {
    $('th, td', this).each( function(i, el) { // nb: implicit column number
        var html = $(this).html();
        if (i in valuesArr) {
            valuesArr[i].push(html);
        } else {
            valuesArr[i] = [ html ];  // new array with one element
        }
    }
});

Upvotes: 2

Samuel Hapak
Samuel Hapak

Reputation: 7192

The push() method adds new items to the end of an array, and returns the new length. So, try to change it:

valuesArr[colNum].push( $(this).html() );  

Just remove the =

Moreover, you need to initialize array before first time using it, try:

valuesArr[colNum] = valuesArr[colNum] ? valuesArr[colNum] : [];

You will find complete working example here http://jsfiddle.net/57A9z/

Upvotes: 1

mihai
mihai

Reputation: 38543

var valuesArr = [];
var r = 0;
var c = 0;

$('#ajaxResponse1 tr').each( function() {
    valuesArr[r] = [];
    $('th, td', this).each( function() {
        valuesArr[r][c] = $(this).html();   
        c++;
    });
    c = 0;
    r++;
});

Upvotes: 0

Related Questions