You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中去重GeoJSON LineString并保留指定属性对象

Filter GeoJSON Array to Remove Duplicate Geometries, Keeping Object with Full maintenanceresponsibility Property

Your existing removeDuplicateGeoms function does a great job detecting duplicate geometries with JSTS, but the issue is that findIndex returns the first matching geometry's index. This means if a duplicate group starts with an object where maintenanceresponsibility is null, that's the one that gets kept—when you need the opposite: prioritize objects with a non-null maintenanceresponsibility in each duplicate group.

Here's a revised implementation that solves this:

import jsts from 'jsts';

export const removeDuplicateGeoms = arr => {
  // Initialize a single JSTS parser to avoid redundant instantiations
  const parser = new jsts.io.GeoJSONReader();

  // Step 1: Group all features by their geometry (using WKT as a unique key)
  const geometryGroups = arr.reduce((groups, feature) => {
    const geomWkt = parser.read(feature.geometry).toText();
    if (!groups[geomWkt]) {
      groups[geomWkt] = [];
    }
    groups[geomWkt].push(feature);
    return groups;
  }, {});

  // Step 2: For each group, pick the feature with non-null maintenanceresponsibility (or first if none exist)
  return Object.values(geometryGroups).map(group => {
    const preferredFeature = group.find(f => f.properties.maintenanceresponsibility !== null);
    return preferredFeature || group[0];
  });
};

How This Works

  1. Grouping by Geometry: We use reduce to cluster all features with identical geometries together. Converting geometries to WKT strings with toText() gives us a reliable unique key for grouping.
  2. Selecting the Preferred Feature: For each group of duplicates, we first look for any feature where maintenanceresponsibility is not null. If we find one, that's the keeper—otherwise, we fall back to the first feature in the group (you could adjust this to pick another fallback if needed).

Testing with Your Sample Data

In your example, the two features share the exact same geometry. The function will group them together, find the second feature with maintenanceresponsibility: "Maintainable At Public Expense", and return only that feature—exactly what you're looking for.

Performance Note

By creating the JSTS parser once outside the loop instead of inside, we avoid unnecessary object creation, which makes the function faster especially with large GeoJSON arrays.

内容的提问来源于stack exchange,提问作者Ian Marett

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 13:53:15