How to Decimate an Array.

Adam Crockett 🌀 - Sep 24 '20 - - Dev Community

An interesting use case arrived yesterday, I loved the simplicity of the code so I thought I'd share it.

Code: boom 💣

export function decimateArray(arr, passes = 1, fidelity = 2) {
  let tmpArr = arr.filter((_, index) => index % fidelity === 0);
  passes--;
  if (passes) {
    tmpArr = decimateArray(tmpArr, passes, fidelity);
  }
  return tmpArr;
}

Enter fullscreen mode Exit fullscreen mode

Use case:

"I have a large array of xy coordinates, I need it to draw freehand on canvas but it's too much data to work with quickly, I just want to draw an approximate polygon. I want the array to be smaller so I can more efficiently loop through the data and I dont care about all of the data just the start and end."

How?

An array is fed in, if the index of the data is modulus of a passed in fidelity then keep this data, also recursively run this dataset through itself by a given number of passes.

In english please?

Large array goes in, smaller array with less detail comes out.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .