Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first array of numbers in array of variable depth

I am using a function 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.

like image 401
JellyRaptor Avatar asked Sep 28 '16 18:09

JellyRaptor


People also ask

How do you get the first data from an array?

There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more. We will discuss the different ways to access the first element of an array sequentially.

What is the first index in a numeric array?

An array element is one value in an array. An array index is an integer indicating a position in an array. Like Strings, arrays use zero-based indexing, that is, array indexes start with 0.

How do I find the first and last index of an array?

The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index. The array length property in JavaScript is used to set or return the number of elements in an array.


1 Answers

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));
like image 181
Redu Avatar answered Oct 09 '22 22:10

Redu