Search code examples
javascriptarraysnode.jsturfjs

Finding every first array in nested array


I have a function that sometimes generates a nested array (for multiPolygon purposes). It could look like this:

[
  [
    [ 10.0, 59.0],
    [ 10.0, 59.0],
    [ 10.0, 59.0]
  ],
  [
    [ 10.0, 59.0],
    [ 10.0, 59.0],
    [ 10.0, 59.0]
  ]
]

So it could return a nested array with multiple nested arrays inside. But i want to make shure that i only get the first nested array, like this:

[
  [
    [ 10.0, 59.0],
    [ 10.0, 59.0],
    [ 10.0, 59.0]
  ]
]

Im developing in NodeJS.


Solution

  • A simple recurrence function which looks for another arrays solves it. It works with infinitely nested arrays and use object type protection.

    function getFirstArray(array){
      var hasArrays = false;
      for (i in array) {
        if(typeof(array[i]) == "object"){
          return getFirstArray(array[i]);
          hasArrays = true;
          break;
        }
      }
      if(!(hasArrays)){
        return array;
      }
    }
    

    Then use it simply as:

    var firstArray = getFirstArray(matrix);
    console.log(firstArray);
    

    Hope this helps :)