Basic Algorithm Scripting: Chunky Monkey

Tell us what’s happening:
Consider the code.
Can you explain, how the nested array are created. Unlike slice() method, the splice() method adds/removes items to/from an array and returns the removed item(s) but it does not return the items in a new array. The push() method does not create a new array either.
How the new nested arrays are created?

Your code so far


function chunkArrayInGroups(arr, size) {
  let arr1 = [];
  while (arr.length) {
     arr1.push(arr.splice(0, size));
  }
  console.log(arr1[0]);
  return arr1;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

Your browser information:

User Agent is: Mozilla/5.0 (X11; CrOS x86_64 11316.148.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.117 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey

Actually, yes it does, you can test this with your own code by logging the splicedResult

function chunkArrayInGroups(arr, size) {
  let arr1 = [];
  while (arr.length) {
     const splicedResult = arr.splice(0, size)
     console.log(splicedResult)
     arr1.push(splicedResult);
  }
  return arr1;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

// [ 'a', 'b' ]
// [ 'c', 'd' ]

And from MDN

Return value - An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

1 Like