Skip to content

Instantly share code, notes, and snippets.

@RavenHursT
Created November 5, 2022 06:49
Show Gist options
  • Save RavenHursT/8e742d82ef6653e609ccb68542462741 to your computer and use it in GitHub Desktop.
Save RavenHursT/8e742d82ef6653e609ccb68542462741 to your computer and use it in GitHub Desktop.
arraySample: An TS/JS array util when you want an evenly distributed sample of values from an array
const arraySample = (array: any[], targetSampleLength: number): any[] => {
const currentLength = array.length
if (currentLength <= targetSampleLength) {
return array
}
const lastIndex = array.length - 1
const increment = Math.ceil(currentLength / targetSampleLength)
let newArray = []
while (newArray.length <= targetSampleLength) {
const i: number = newArray.length === 0 ?
0 : newArray.length * increment
if (
newArray.length === targetSampleLength - 1
){
newArray.push(array[lastIndex])
break
} else {
newArray.push(array[i])
}
}
return newArray
}
@RavenHursT
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment