Reputation: 7526
I have a for loop that logs the coordinate array of each feature in my feature layer. Oddly, however, the 33rd element of the feature layer is an array of 3 arrays - with lengths 16, 58, and 246. How can I access these arrays which are one level deeper - and log them to the console as well?
if (data.features.length > 0) {
for(var i = 0; i < features.length; i++){
console.log(i, features[i].geometry.coordinates)
}
}
Upvotes: 1
Views: 222
Reputation: 18968
Another Solution is to just check if the Object inside an array is an instance of an Array or not.
If it is an instance of another array just call that function recursively.
The solution looks like the following:
var arr = [1, 2, [4,5,6], [9,5,6,7]];
printArray(arr);
printArray(null);
function printArray(arr){
if(arr == null || arr == undefined){
return;
}
if(arr.length == 0){
return;
}
for(var i = 0; i < arr.length; i++){
if(arr[i] instanceof Array){
printArray(arr[i]);
} else{
console.log(arr[i]);
}
}
}
Upvotes: 0
Reputation: 10396
You can use recursion like below:
function iterateArray(array) {
array.forEach((item) => {
if (Array.isArray(item)) {
iterateArray(item);
}
else {
console.log(item);
}
});
}
var array = [1, 2, [3, 4, 5], [6, [7, [8, 9]]]];
iterateArray(array);
Upvotes: 3