turf.segmentReduce
What is turf.segmentReduce?
turf.segmentReduce folds every two-vertex segment in a GeoJSON object into one accumulator, with the segment yielded as a LineString Feature.
turf.segmentReduce(geojson, callback, initialValue?) → anyThe callback receives (previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex).
When would you use turf.segmentReduce?
Use turf.segmentReduce for per-edge accumulations — total network length (identical to turf.length when summed with unit care), counts of steep edges, or maps from edge id to bearing.
It avoids materialising all segments into a flat array (as a manual flattenEach + loop would), which keeps memory flat even on very large road networks.
1const totalLength = turf.segmentReduce(
2 network,
3 (sum, seg) => sum + turf.length(seg, { units: 'meters' }),
4 0
5);FAQs
How do I install Turf.js to use this function?
Install npm install @turf/meta and import import { segmentReduce } from '@turf/meta', or use turf.segmentReduce via the umbrella @turf/turf.
Are the segments Features or raw arrays?
Each is a two-vertex LineString Feature — so you can pass it directly to turf.length, turf.bearing, or any line-accepting function.
Does segmentReduce process polygon rings?
Yes. Outer and inner rings contribute their edges too. If you want only line geometries, filter your input first.
When should I use segmentReduce vs length?
turf.length computes the length of a single line in one call. segmentReduce is the right tool when your accumulation is not a plain length — for example counting segments, bucketing by bearing, or returning a non-scalar result.