0

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:

  1. Whats wrong with my code example?
  2. 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!

Matt Pengelly
  • 1,480
  • 2
  • 20
  • 34

1 Answers1

1

A simpler way to do this would be:

let size = 2;
[1, 2, 3, 4, 5, 6, 7, 8].reduce((carry, current, index) => {
    // get the current array bucket.  if it doesn't exist, create it.
    let el = carry[Math.floor(index / size)] = carry[Math.floor(index / size)] || [];
    // push the current element onto the current bucket
    el.push(current);
    // return our new array
    return carry;
}, [])

The issue with your code is just that you need to do:

tempArr.push(arr[i + count])
dave
  • 62,300
  • 5
  • 72
  • 93