Created
April 2, 2019 19:13
-
-
Save GingerBear/e27476bb52bc8902d388b01e01e62822 to your computer and use it in GitHub Desktop.
sample Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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