tibsar - 1 year ago 88

Javascript Question

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

`outline.geometry.coordinates`

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

For a point, calling

`point.geometry.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], ...]]`

First, I tried to get all of the coordinates, where

`geometries`

`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?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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 ] ]
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**