turf.clusterReduce
What is turf.clusterReduce?
turf.clusterReduce groups a FeatureCollection by a property and folds each cluster into an accumulator, yielding the sub-FeatureCollection and cluster value on every iteration.
turf.clusterReduce(geojson, property, callback, initialValue?) → anyThe callback receives (previousValue, cluster, clusterValue, currentIndex).
When would you use turf.clusterReduce?
Use turf.clusterReduce to compute per-cluster aggregates and collect them into a single structure — an array of cluster centroids, a map from cluster id to mean property value, or a summary object you can render in a sidebar.
It is essentially clusterEach + outer accumulator, with the same advantages reduce has over forEach: explicit return, no shared mutable state.
1const clustered = turf.clustersKmeans(points, { numberOfClusters: 3 });
2const centroids = turf.clusterReduce(
3 clustered,
4 'cluster',
5 (acc, cluster, id) => {
6 acc.push({ id, center: turf.centroid(cluster) });
7 return acc;
8 },
9 []
10);FAQs
How do I install Turf.js to use this function?
Install npm install @turf/clusters and import import { clusterReduce } from '@turf/clusters', or use turf.clusterReduce via the umbrella @turf/turf.
How does it differ from featureReduce?
featureReduce visits each Feature once. clusterReduce first groups features by a property, then visits each cluster as a unit — useful when the reduction operates per-group rather than per-feature.
What if two features have the same cluster value?
They are yielded together inside one sub-FeatureCollection on the same iteration — that is the entire point of clustering.
Can I use it without a clustering algorithm?
Yes. Any property can serve as the grouping key — clusterReduce(fc, 'zoneId', ...) groups by zone id regardless of whether clustering was applied.