Turf.jsMeta

turf.flattenEach

What is turf.flattenEach?

turf.flattenEach iterates over every geometry of any GeoJSON input, splitting MultiPoint, MultiLineString, and MultiPolygon into their single-part components. The callback receives one Feature per primitive geometry, each carrying a copy of the original properties.

JavaScript
turf.flattenEach(geojson, callback)void

The callback is invoked with (currentFeature, featureIndex, multiFeatureIndex).

When would you use turf.flattenEach?

Use turf.flattenEach when downstream code (for example a renderer or a spatial predicate) needs single-part geometries. It saves you a manual turf.flatten + iterate pass.

It is also useful when you want to index multi-part features by part — for example assigning a part id in the multiFeatureIndex callback argument, or producing an adjacency list of polygon pieces.

JavaScript
1turf.flattenEach(fcWithMultiPolygons, (feature, featureIndex, multiIndex) => {
2  feature.properties.partId = `${featureIndex}-${multiIndex}`;
3  output.push(feature);
4});

FAQs

How do I install Turf.js to use this function?

Install npm install @turf/meta and import import { flattenEach } from '@turf/meta', or use turf.flattenEach from @turf/turf.

Does flattenEach mutate the input?

No. It yields freshly constructed single-part Features, leaving the original GeoJSON intact. Mutations you make inside the callback affect only the yielded feature (which is a new object).

What indices does the callback receive?

Three: featureIndex identifies which original Feature the part belongs to; multiFeatureIndex is the sub-part index within that Feature's multi-geometry (0 for single-part geometries).

When should I use flattenEach vs geomEach?

geomEach yields geometries (including the multi-variants themselves). flattenEach yields Features whose geometries are always single-part. Choose flattenEach whenever you want to treat every primitive as an independent unit.