turf.sample
What is turf.sample?
turf.sample takes a FeatureCollection and returns a new FeatureCollection containing num random features drawn from it. Each pick is independent — the function does not guarantee a different subset across calls, but repeats within a single call are avoided.
turf.sample(featureCollection, num) → FeatureCollectionParameters:
featureCollection— input collection to draw fromnum— number of features to return
When would you use turf.sample?
Use turf.sample when you have a real dataset and want to downsample it — previewing a 50,000-feature tileset with a manageable 1,000-feature collection, selecting a random test batch for QA, or drawing a representative handful of parcels to inspect manually before a full processing run.
Unlike turf.randomPoint, which invents new points, turf.sample preserves the original properties and geometries, so any downstream styling or analysis behaves as it would on the full dataset.
1const big = turf.randomPoint(10000, { bbox: [-122.6, 37.6, -122.3, 37.9] });
2const preview = turf.sample(big, 200);
3map.getSource('preview').setData(preview);FAQs
How do I install Turf.js to use this function?
Install npm install @turf/sample and import with import { sample } from '@turf/sample', or use the bundled turf.sample from @turf/turf.
Is sampling with replacement?
No — Turf's sample picks without replacement within a single call, so no feature appears twice. Each call is independent, however, so running it twice can return overlapping subsets.
What happens if num is larger than the collection?
Turf will happily return a collection no larger than the input; behaviour at the boundary depends on the current implementation and may include duplicates or fewer features than requested. Clamp num to features.length in your code to avoid surprises.
Can I seed the sampler for reproducible results?
No, there is no seed parameter — it uses Math.random(). If you need a deterministic subset, shuffle your array with a seeded PRNG of your choice and slice the first num features manually.