Skip to content

Instantly share code, notes, and snippets.

@kopasetik
Last active March 16, 2017 23:32
Show Gist options
  • Save kopasetik/c466b87af369b95bb2010595b683c0ce to your computer and use it in GitHub Desktop.
Save kopasetik/c466b87af369b95bb2010595b683c0ce to your computer and use it in GitHub Desktop.
JS Array Segmentation
function fSegment(arr, maxLength){
return arr.reduce((acc, curr, idx, artie) => {
if(idx * maxLength >= artie.length) return acc
var upperLimit = (maxLength > artie.length) ? artie.length: (idx + 1) * maxLength
acc[idx] = artie.slice(idx * maxLength, upperLimit)
return acc
}, [])
}
function pSegment(arr, maxLength){
var segmented = []
for (var counter = 0; counter * maxLength < arr.length; counter++){
if(maxLength > arr.length){
segmented.push(arr.slice(counter * maxLength, arr.length))
} else {
segmented.push(arr.slice(counter * maxLength, (counter + 1) * maxLength))
}
}
return segmented
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment