3

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.

1 Answer 1

4

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());
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

I knew the solution was probably simple but didn't think it would be that simple! Thanks
hi how can i put variable key into your solution?
I have similar code as below but I am getting erro: 0x800a138f - JavaScript runtime error: Unable to get property 'push' of undefined or null reference $.each(data.data, function (index, item) { debugger; if (item.Dataset != '' && item.Dataset >= 0) { var date = item.DateCreated.replace(/\//g, "").replace('Date', " ").replace('(', "").replace(')', ""); arrObject[parseInt(date)].push($(parseFloat(item.Dataset))); } });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.