Get the first array of numbers in an array of variable depth

I use a method in a javascript structure where the return value can be ANY of the following

  • one coordinate pair xy

    [x,y] 
  • array of xy coordinate pairs

     [[x,y],[x,y],...] 
  • array of arrays of xy coordinate pairs

     [[[x,y],[x,y]],[[x,y],[x,y]],...] 

The return value depends on the geometry of the object (single point, line, or several lines). Regardless of the return value and its depth of the array, I want to capture the first xy coordinate pair. What is an effective way to do this?

Here is my code to achieve the goal so far:

 //here is the magic method that can return one of three things :) var mysteryCoordinates = geometry.getCoordinates(); var firstCoord; if(typeof mysteryCoordinates[0] === 'number') { firstCoord = mysteryCoordinates; } else if (typeof mysteryCoordinates[0][0] === 'number') { firstCoord = mysteryCoordinates[0]; } else if (typeof mysteryCoordinates[0][0][0] === 'number') { firstCoord = mysteryCoordinates[0][0]; } 

I really hate this solution and am looking for something more elegant.

+7
javascript arrays multidimensional-array
source share
2 answers

I think in pure JS this should be done;

 var arr = [[[1,2],[1,3]],[[4,8],[3,9]]], getFirstXY = a => Array.isArray(a[0]) ? getFirstXY(a[0]) : a; console.log(getFirstXY(arr)); 
+4
source share

A less efficient but more elegant solution would be to use _.flatten ( http://underscorejs.org/#flatten ):

 let firstCoord = _.flatten(mysteryCoordinates).slice(0, 2); 

You can make this a bit more efficient on average by cutting the first two elements forward:

 let firstCoord = _.flatten(mysteryCoordinates.slice(0, 2)).slice(0, 2); 

 console.log(_.flatten([1,2]).slice(0, 2)); console.log(_.flatten([[1,2],[1,3],[4,8],[3,9]]).slice(0, 2)); console.log(_.flatten([[[1,2],[1,3]],[[4,8],[3,9]]]).slice(0, 2)); 
 <script src="http://underscorejs.org/underscore-min.js"></script> 
+2
source share

All Articles