Skip to content

Instantly share code, notes, and snippets.

@evaporei
Last active October 11, 2021 14:23
Show Gist options
  • Save evaporei/5a4ed304a06f5458039d907e69a21f22 to your computer and use it in GitHub Desktop.
Save evaporei/5a4ed304a06f5458039d907e69a21f22 to your computer and use it in GitHub Desktop.
JS contiguous array chunks
const getChunk = (arr, from, size) => {
const clampedFrom = (from + size) > arr.length
// Trying to get chunk bigger than end of array.
// Here we reduce `from` so that the chunk size is always preserved.
? arr.length - size
: from
return arr.slice(clampedFrom, from + size)
}
const array = [1,2,3,4,5]
const chunkSize = 2
const result = array
.map((item, index) => getChunk(array, index, chunkSize))
// This is needed to remove extra pair.
// This pair happens because the result array should be of size equal
// to input.length - 1.
// Example:
// input: [1, 2, 3] (length = 3)
// output: [[1,2], [2,3]] (length = 2)
result.pop()
console.log('result', result)
// result [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ] ]
@evaporei
Copy link
Author

evaporei commented Oct 9, 2021

Oops there's a bug of a double item in the end (two 4,5), I'm gonna fix that tomorrow.

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