I have an arrays of arrays (some thing like graph), How to iterate all arrays?
var parentArray = [
[[1,2,3],[4,5,6],[7,8,9]],
[[10,11,12],[13,14,15],[16,17,18]],
[[19,20,21],[22,23,24],[26,27,28]]
];
Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM
This recursive function should do the trick with any number of dimensions:
var printArray = function(arr) {
if ( typeof(arr) == "object") {
for (var i = 0; i < arr.length; i++) {
printArray(arr[i]);
}
}
else document.write(arr);
}
printArray(parentArray);
For 2 dimenional Arrays:
for(var i = 0; i < parentArray.length; i++){
for(var j = 0; j < parentArray[i].length; j++){
console.log(parentArray[i][j]);
}
}
For arrays with an unknown number of dimensions you have to use recursion:
function printArray(arr){
for(var i = 0; i < arr.length; i++){
if(arr[i] instanceof Array){
printArray(arr[i]);
}else{
console.log(arr[i]);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With