tibsar tibsar - 4 months ago 12
Javascript Question

Partially flatten multidimensional array

I have an array of outlines and points. For an outline, calling

outline.geometry.coordinates
produces a multidimensional array of coordinates:

[[[-72.68639118392117,41.66733032827929],[-72.68630366033922,41.667449647115724], ...]]


For a point, calling
point.geometry.coordinates
produces a one dimensional array of the coordinates:

[-72.78630766033722,41.767349642115724]


Both points and outlines are held in an array. I would like to ultimately end up with an array of all of the coordinate pairs, such as:

[[[-72.68639118392117,41.66733032827929],[-72.68630366033922,41.667449647115724],[-72.78630766033722,41.767349642115724], ...]]





What I've Tried

First, I tried to get all of the coordinates, where
geometries
is my array of outlines and points:

var coordinates = geometries.map(function(outline) {return outline.geometry.coordinates});


Not surprisingly, this creates the following array:

[[[[-72.68639118392117,41.66733032827929],[-72.68630366033922,41.667449647115724], ...]], [-72.78630766033722,41.767349642115724]]


Flattening this array would cause loss of the coordinate pairs being paired, so I'm not entirely sure how to go about this. Any ideas?

Answer

How about this?

var geometries = [
    // point
    {
        geometry: {
            coordinates: [1, 2],
        },
    },

    // outline
    {
        geometry: {
            coordinates: [
                [3, 4],
                [5, 6],
            ]
        },
    },
];

var coordinates = geometries.map(function(outline) {
  var coords = outline.geometry.coordinates;
  if (typeof coords[0] === 'number') {
    return [coords];
  } else {
    return coords;
  }
}).reduce(function (prev, next) {
    return prev.concat(next);
}, []);

console.log(coordinates);

// Output:
// [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
Comments