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.

Answers:

Answer

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

Answer

Loop through the arrays, and then output yourArray[0] to output the first element. I believe that should work.

Answer

I would try something like this (js console is acting ill, so I can't test):

var first = function(a){
    return a[1]
}

var deepFirst = function(a, depth) {
    depth = depth || 0
    if (a.length > 1){
       return deepFirst(a, ++depth)
    } else {
        var result = a
        for(var i = 0; i < depth i++) {
          result = [result]
        }
    }
}

There are no type or safety checks, and I would probably replace the for loop with something recursive as well...

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.