garethdn
garethdn

Reputation: 12351

How to push values to a multi-dimensional array

I can't figure out how to push values to a dynamic multi-dimensional array. This is the code i have:

function compareNumbers(){
    var count = $('.finishedRow').length;
    var inputtedNums = new Array();
    for(var i=0; i<count; i++){
        $('.finishedRow').eq(i).find('li').each(function(j){
            inputtedNums[i].push($(this).text());
        });
    }
    console.log(inputtedNums);
}

So say there are, for example, 3 finishedRow selectors and each finishedRow selector contains 4 li elements with values of first, second, third, fourth. I want my inputtedNums variable to look like:

inputtedNums = [
   ["first", "second", "third", "fourth"],
   ["first", "second", "third", "fourth"], 
   ["first", "second", "third", "fourth"] 
]

As my code is now I get the error: Cannot call method 'push' of undefined.

I'm sure I'm missing something fundamental here.

Upvotes: 3

Views: 3267

Answers (1)

Matthias
Matthias

Reputation: 7521

You need to initialize every nested array first.

for(var i = 0; i < count; i++) {
    inputtedNums[i] = new Array();
    $('.finishedRow').eq(i).find('li').each(function(j) {
        inputtedNums[i].push($(this).text());
    });
}

Upvotes: 4

Related Questions