Skip to content

Instantly share code, notes, and snippets.

@GingerBear
Created April 2, 2019 19:13
Show Gist options
  • Save GingerBear/e27476bb52bc8902d388b01e01e62822 to your computer and use it in GitHub Desktop.
Save GingerBear/e27476bb52bc8902d388b01e01e62822 to your computer and use it in GitHub Desktop.
sample Array
function sampleArray(arr, num) {
if (arr.length <= num) {
return arr;
} else {
const every = Math.floor(arr.length / num);
const sampleIndex = Array(num)
.fill(0)
.map((_, i) => i * every);
// keep last element
if (sampleIndex[sampleIndex.length - 1] < arr.length - 1) {
sampleIndex.push(arr.length - 1);
}
return sampleIndex.map(i => arr[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment