1

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?

enter image description here

if (data.features.length > 0) {
    for(var i = 0; i < features.length; i++){
        console.log(i, features[i].geometry.coordinates)
    }
}

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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]);
        }
    }
}

Comments

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.