如何在JavaScript中去重GeoJSON LineString并保留指定属性对象
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
- Grouping by Geometry: We use
reduceto cluster all features with identical geometries together. Converting geometries to WKT strings withtoText()gives us a reliable unique key for grouping. - Selecting the Preferred Feature: For each group of duplicates, we first look for any feature where
maintenanceresponsibilityis notnull. 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

