Turf.jsMeta

turf.flattenReduce

What is turf.flattenReduce?

turf.flattenReduce folds all single-part Features of a GeoJSON object into one accumulator. It internally flattens MultiPoint/MultiLineString/MultiPolygon into their primitives before reducing.

JavaScript
turf.flattenReduce(geojson, callback, initialValue?) → any

The callback receives (previousValue, currentFeature, featureIndex, multiFeatureIndex).

When would you use turf.flattenReduce?

Use turf.flattenReduce whenever a multi-geometry should contribute once per part rather than once per parent Feature — for example counting the total number of islands across a MultiPolygon dataset, summing the length of every line segment in a MultiLineString network, or building a flat lookup by (featureIndex, multiFeatureIndex).

JavaScript
1const islandCount = turf.flattenReduce(
2  countries,
3  (count, _part, featureIndex, multiIndex) => count + 1,
4  0
5);

FAQs

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

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

How does flattenReduce differ from featureReduce?

featureReduce visits each original Feature once — a MultiPolygon is a single iteration. flattenReduce visits every sub-geometry once, so a MultiPolygon with three islands yields three iterations.

Does the callback receive a cloned feature?

Yes — each iteration yields a freshly built single-part Feature so mutations do not leak into the original GeoJSON.

When is flattenReduce the wrong choice?

When you need the context of the parent Feature (its full properties plus which part belongs to which parent), you already have it via featureIndex and multiFeatureIndex. But if you need properties to reflect part-specific values, attach them before flattening.