DEV Community

Discussion on: Array Chunking

Collapse
 
ripaz profile image
Ripaz

Can you elaborate why is that?

Collapse
 
ycmjason profile image
YCM Jason

This is because Array.prototype.splice does whatever it does in place. Meaning that it mutates the original array. Mutation are usually consider to make code hard to reason about unless it is very explicit (like obj.setName('jason')).

Going back to the chunk example, consider the following code:

const arr = [1,2,3,4,5,6,7,8,9];
const chunks = chunk(arr, 3);

console.log(chunks);
console.log(arr);

What would you expect to be logged? I guess you would probably expect:

[[1,2,3], [4,5,6], [7,8,9]] // chunks
[1,2,3,4,5,6,7,8,9] // arr

But since Ryan suggested to use splice, it edits our arr in place. And the actual log you will see is:

[[1,2,3], [4,5,6], [7,8,9]] // chunks
[] // arr

A way to fix this is to clone the whole array before doing anything.

function chunk(array, size) {
  // clone the array to avoid touching the original one.
  array = array.slice(0)
  //declaring variable 'chunked' as an empty array
  let chunked = []

  //looping through the array until it has been entirely "manipulated" or split into our subarrays
  while(array.length > 0) {
    //taking the spliced segments completely out of our original array
    //pushing these subarrays into our new "chunked" array
    chunked.push(array.splice(0, size))
  }
  //returning the new array of subarrays
  return chunked
}

Or a more ES6+ method using array spread (preferable):

function chunk([...array], size) {
  //declaring variable 'chunked' as an empty array
  let chunked = []

  //looping through the array until it has been entirely "manipulated" or split into our subarrays
  while(array.length > 0) {
    //taking the spliced segments completely out of our original array
    //pushing these subarrays into our new "chunked" array
    chunked.push(array.splice(0, size))
  }
  //returning the new array of subarrays
  return chunked
}

I hope I explained this properly.

Thread Thread
 
basitali profile image
Basit Ali Mundia

Couldn't have explained it better.

Thread Thread
 
ryanfarney3 profile image
Ryan Farney

Thank you Basit and Jason for clearing this up! I certainly should have mentioned the dangers of mutating our original dataset.

Nonetheless, having knowledge of how to use .splice as well as it's dangers could show mastery of JS in the context of an interview <3