turf.clusterEach
What is turf.clusterEach?
turf.clusterEach groups a FeatureCollection by a property and iterates over the resulting clusters, calling a callback once per unique cluster value with a sub-FeatureCollection of its members.
turf.clusterEach(geojson, property, callback) → voidThe callback receives (cluster, clusterValue, currentIndex).
When would you use turf.clusterEach?
Use turf.clusterEach after turf.clustersKmeans or turf.clustersDbscan (or any workflow that labels Features with a cluster id) when you need per-cluster statistics — centroids, convex hulls, summary counts — without running a separate getCluster call for each label.
It is also useful for grouping-then-aggregating tasks on any property, not just cluster ids — the argument property can be any attribute you want to group by.
1const labelled = turf.clustersKmeans(points, { numberOfClusters: 4 });
2turf.clusterEach(labelled, 'cluster', (cluster, clusterId) => {
3 const centroid = turf.centroid(cluster);
4 centroid.properties.clusterId = clusterId;
5 centroids.push(centroid);
6});FAQs
How do I install Turf.js to use this function?
Install npm install @turf/clusters and import import { clusterEach } from '@turf/clusters', or use turf.clusterEach from @turf/turf.
Can I group by any property, not just `cluster`?
Yes. The second argument is the property name to group on — for example clusterEach(fc, 'zoneId', callback) groups by zone.
What if a Feature has no value for the property?
Features missing the property are excluded from iteration. If you want them captured, assign a sentinel value beforehand with turf.propEach.
Should I use clusterEach or getCluster?
Use clusterEach when you want every group in one pass. Use getCluster when you need only one specific group.