Lodash chunk() Alternative Solution without slice

In this solution I was accessing multidimensional array directly. I realized that the first dimension had to be initialized first, otherwise it would throw TypeError.

chunk(arr, size = 1) {
//for size equal to array length, we keep as is.. not clear from the instructions
      if (size === arr.length)
        return arr
      let newarr = []
      for (let i=0; i<arr.length/size;i++)
       newarr[i] = []
        for (let i=0; i<arr.length; i++)
          newarr[Math.floor(i/size)][i%size] = arr[i]
        return newarr
    }
1 Like

To my mind,

chunk([1, 2, 3, 4], 4)

should return, [ 1, 2, 3, 4 ], and not, [ [ 1, 2, 3, 4 ] ] but that needs further exploring to confirm. My logic looking at just the code.

Could you please post a link to the instructions for this method? Thanks.

https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-javascript-syntax-part-ii/modules/fecp-practice-javascript-syntax-arrays-loops-objects-iterators/projects/lodash

Point 39 - not clear to me, as well… but good catch

1 Like

Creates an array of elements split into groups the length of size .

Which means the return from your code is correct.

const print = console.log;
const chunk = function (arr, size = 1) {
  let newarr = []
  for (let i = 0; i < arr.length / size; i++)
    newarr[i] = []
    for (let j = 0; j < arr.length; j++)
      newarr[Math.floor(j / size)][j % size] = arr[j]
  return newarr
}
print (chunk([1, 2, 3, 4], 5))
print (chunk([1, 2, 3, 4], 4))
print (chunk([1, 2, 3, 4], 3))
print (chunk([1, 2, 3, 4], 2))
print (chunk([1, 2, 3, 4], 1))
//print (chunk([1, 2, 3, 4], 0))  // will cause a memory overflow
[ [ 1, 2, 3, 4 ] ]
[ [ 1, 2, 3, 4 ] ]
[ [ 1, 2, 3 ], [ 4 ] ]
[ [ 1, 2 ], [ 3, 4 ] ]
[ [ 1 ], [ 2 ], [ 3 ], [ 4 ] ]