I'm trying to implement a chunk function in javascript similar to lodash chunk. It seems like i'm hitting an indexing issue relating to the count here but I can't figure it out.
// chunk array function breaks an array into chunks of defined size
// [1, 2, 3, 4, 5, 6, 7, 8]
// with size 2
// should output: [[1,2], [3,4], [5,6], [7,8]]
const testArr = [1, 2, 3, 4, 5, 6, 7, 8]
const testArr2 = [1, 2, 3, 4, 5, 6, 7]
function chunk(arr, size){
let newArr = []
let tempArr = []
let iterations;
let remainder;
if(Number.isInteger(arr.length / size)){
iterations = arr.length / size
} else {
iterations = size.toString().split('.')[0]
// how many remain?
remainder = arr.length % size
}
// theres an issue somewhere in here relating to count
let count = 0
while(count < iterations){
tempArr = []
for(let i = count; i < (size + count); i++){
tempArr.push(arr[i])
}
newArr.push(tempArr)
count++
}
// if(remainder){
// for(let i = count; i < count + remainder; i++){
// tempArr.push(arr[i])
// }
// }
return newArr
}
console.log(chunk(testArr, 2))
I'm interested in 2 different things:
- Whats wrong with my code example?
- How would YOU implement this better? Clearly my example is not very clean and I'm curious how others would handle it (some .map .reduce stuff maybe?) i tried reading lodash docs but they use a lot of internal functions that make it a little confusing.
actual output is: [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ] ]
output should be: [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ] ]
Thanks!