0

I have a geojson feature collection with features like below in the entire collection.

{ geometry: { coordinates: [Array], type: 'LineString' },
properties: { angle: 120.2},
type: 'Feature' }

Is there a way which I can randomise the features in the collection and make them not sequential in javascript?

csvb
  • 365
  • 2
  • 6
  • 14

1 Answers1

1

You can just use Array#sort combined with Math.random.

const features = [{
  geometry: {
    coordinates: [Array],
    type: 'LineString'
  },
  properties: {
    angle: 120.2
  },
  type: 'Feature'
}, {
  geometry: {
    coordinates: [Array],
    type: 'LineString'
  },
  properties: {
    angle: 100.2
  },
  type: 'Feature'
}, {
  geometry: {
    coordinates: [Array],
    type: 'LineString'
  },
  properties: {
    angle: 4.2
  },
  type: 'Feature'
}, {
  geometry: {
    coordinates: [Array],
    type: 'LineString'
  },
  properties: {
    angle: 15.2
  },
  type: 'Feature'
}]

const randomSort = (arr) => {
  return arr.sort(() => {
    return 0.5 - Math.random()
  })
}

console.log(randomSort(features))
dzm
  • 22,844
  • 47
  • 146
  • 226
  • I dont want to pick the random feature. But want to randomly sort the features in the collection. – csvb Nov 07 '17 at 19:47