Start New Discussion within our Web Development Community

Hi, i have a 2D array animal and i want to copy it to another 2D array myArray. can somehelp? the code below is not working. I am havine this error :
Uncaught TypeError: Cannot set property '0' of undefined on line 7

var test="";
var myArray=new Array(animal.length);
    for (y=0;y<animal.length;y++){
        myArray=new Array(animal.length);
        for(x=0;x<animal.length;x++){
            test=""+animal[y][x].text;
            myArray[y][x]=test;
        }   
    }
    alert(myArray);

yes thanks. can you tell me how to retrieve all element from a 2D array column wise?

the code below is retrieving the first five element in each column. I want it to retrieve all element in column 1, then it goes to column 2 n retrieve and so on..

var myArray=new Array();
function animal(){
        var test="";
        for(var i=0;i<10;++i){ 
            myArray[i]=new Array();
            for(var j=0;j<10;++j){
                test=""+myArray[i][j] + myArray[i+1][j]+ myArray[i+2][j] + myArray[i+3][j] + myArray[i+4][j];

                alert(test)
            }
        }
}
function animal(){
        var test="";
        for(var i=0;i<10;++i){ 
            myArray[i]=new Array();
            for(var j=0;j<10;++j){
                test=""+myArray[i][j] + myArray[i][j+1]+ myArray[i][j+2] + myArray[i][j+3] + myArray[i][j+4];
                alert(test)
            }
        }
}

how ?
like this?

well this one it retrieves the element by row. i want it to retrieve by column

Although it's clear to you what you want, it's not to me. Can you show an example with some data to explain? What you have, and what output you want.

i have a table like this:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

assume it is a table (5 by 5).i generate this table using a 2D array. i want to retrieve element by column.
Example:
1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25

the code above when reversing the indexes like you said will return me this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

Is it clear now? I want it to return me this one : 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25 (by column)

Are you sure you've not made a typo? This works like you asked:

<html>
<body>
<script>
// create array
var myArray = new Array(5);
for (var i = 0; i < 5; i++) {
    myArray[i] = new Array(5);
    for (var j = 0; j < 5; j++) {
        myArray[i][j] = 1 + (i * 5) + j;
    }
}

// by row
for (var i = 0; i < 5; i++) {
    for (var j = 0; j < 5; j++) {
        alert(myArray[i][j]);
    }
}

// by column
for (var i = 0; i < 5; i++) {
    for (var j = 0; j < 5; j++) {
        alert(myArray[j][i]);
    }
}
</script>
</body>
</html>
This article has been dead for over six months. Start a new discussion instead.