How to Merge Two FeatureCollections with Turf

turfwfs

I'm considering implementing a WFS client that, each time the map's view area is moved, fetches the features within that bounding box, and combines them with features previously fetched. Much of the time there will be features downloaded that already exist in the "previously fetched" dataset, so these need to be not duplicated.

Is there a Turf operation to merge two FeatureCollections in this way? I can't see such a thing. union combines two different polygons into a new one. combine combines Point/LineString/Polygon features into MultiPoint/MultiLineString/MultiPolygon.

Best Answer

Unless there's something more complicated that I can't see, couldn't you simply use regular javascript to concatenate the two features array and then build a new FeatureCollection from there? As in :

//ES5
turf.featureCollection(a.features.concat(b.features));

//ES6
turf.featureCollection([...a.features,...b.features]);

Edit to reflect changes in the question and the comment regarding duplicated features :

Considering you don't want to keep both versions of an existing feature, and that they share an id, doesn't the solution become a simple case of filtering features that already exist from the new data? Or maybe is it again too naïve?

Assuming a was generated on the first call and b is the newer data, and id is the property you want to filter on (on two lines to simplify readability).

const existingFeatureIds = a.features.map(feature => feature.properties.id);
turf.featureCollection(a.features.concat(b.features.filter(feature => !existingFeatureIds.includes(feature.properties.id))));
Related Question