JellyRaptor JellyRaptor - 2 months ago 15
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

    [x,y]

  2. an array of xy coordinate pairs

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

  3. an 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 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.

Answer

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;

console.log(getFirstXY(arr));

Comments