noneJavaScript
noneJavaScript

Reputation: 845

How to build an Array of Array with JavaScript?

My output should be like this: (eg. data)

myArray = [ [otherArray0], [otherArray1], [otherArrayN] ]

My try:

var myArray = [];
var num = 50;
for (i=0; i<num;i++)
{

    var a = 0;
    $('#divID .class select[value!=""]').each(function() //get values from a select
    {
        var otherArray+i = []; //each for cycle is a new "sub array"
        otherArray+i[a] = $(this).val(); //store in array the values from select
        a++
     })
}

Am I thinking well?

Upvotes: 0

Views: 133

Answers (4)

Barmar
Barmar

Reputation: 780994

Reading between lots of lines, I think this is what you want:

var myArray = [];
$("#divID .class select").each(function() {
    var subarray = [];
    $("option[value!='']", $(this)).each(function() {
        subarray.push($(this).val());
    });
    myArray.push(subarray);
}

myArray will then contain:

[[sel1Opt1, sel1Opt2, sel1Opt3, ...], [sel2Opt1, sel2Opt2, sel3Opt3, ...], ...]

Upvotes: 1

Plynx
Plynx

Reputation: 11461

A pattern of setting up an empty array ([]) then using push to fill it as you go, then pushing the array onto your final array should take you far.

var myArray = [];
for (int i=0; i<50; i++)
{
    var otherArray = [];
    $(/*...*/).each(function()
    {
       var val = /*...*/;
       otherArray.push(val);
    });
    myArray.push(otherArray);
}

Upvotes: 2

luckystars
luckystars

Reputation: 1754

var num = 50;
for (i=0; i<num;i++)
{
var myArray[i] = array ();
var a = 0;
$('#divID .class select[value!=""]').each(function() //get values from a select
{
    myArray[i].push( $(this).val()); //store in array the values from select

})
}

Upvotes: 0

Jamiec
Jamiec

Reputation: 136104

Firstly

otherArray[i] = []; // create a new array

Then

otherArray[i][a] = $(this).val();

But your code can be made a lot simpler

var myArray = [];
var num = 50;
for (i=0; i<num;i++)
{
    myArray.push($.map($('#divID .class select[value!=""]'),function(e){
        return e.val();
    }));
}

Upvotes: 7

Related Questions