经纬志
首页 / Turf.js / API 文档

clusterEach

先看结论

按属性把要素分组后逐组遍历,回调里可以直接产出统计结果。

最后验证 2026-11-03 · Turf.js 7.x · 更新 2026-10-27 · 引用本文
turf.clusterEach(geojson, property, callback) → void

参数

参数类型说明
geojsonFeatureCollection待分组的数据
propertystring分组字段名
callbackfunction参数为 cluster、value、index

返回值

无返回值。结果通过回调自行收集,或在回调里写回要素属性。

示例

var stats = [];

turf.clusterEach(points, 'type', function (cluster, type, index) {
  var sum = 0;
  turf.featureEach(cluster, function (f) { sum += f.properties.v; });
  stats.push({ type: type, count: cluster.features.length, sum: sum });
});

console.log(stats);

与 clusterReduce 的分工

clusterEach 适合有副作用的遍历,例如写库、画图、累积外部数组。 clusterReduce 适合纯汇总,直接把每组的结果归约成一个数组返回。

字段缺失

分组字段缺失的要素会归到键为 undefined 的一组。 统计前补默认值,或在回调里跳过该组。

顺序不保证。分组按首次出现的顺序排列, 依赖固定顺序的输出要自己排序。

引用本文

经纬志(2026)。《clusterEach》。https://www.jingweizhi.com/turf/api/cluster-each.html(访问日期 2026-11-03)。