JellyRaptor JellyRaptor - 26 days ago 5x
Javascript Question

Get first array of numbers in array of variable depth

I am using a method in a javascript framework where the return value can be ANY of the following

  1. a single xy coordinate pair


  2. an array of xy coordinate pairs


  3. an array of arrays of xy coordinate pairs


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

Here is my code to achieve the objective 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 a bit more elegant.


I guess in pure JS this should do it;

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