DEV Community

Randy Rivera
Randy Rivera

Posted on • Updated on

Writing A Function That Splits An Array Into Groups The Length Of Size And Returns Them As A two-Dimensional Array.

function chunkArrayInGroups(arr, size) {
  return arr;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);
Enter fullscreen mode Exit fullscreen mode
  • Answer:
function chunkArrayInGroups(arr, size) {
  let newArr = [];

  while (arr.length) {
    newArr.push(arr.splice(0, size));
  }

  return newArr;
}

console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2)); // will display [["a", "b"], ["c", "d"]]
Enter fullscreen mode Exit fullscreen mode

Notes:

  • Firstly, we create a variable. newArr is an empty array which we will push to.
  • Our while loop loops until we dont have a length of the array.
  • Inside our loop, we push to the newArr array using arr.splice(0, size).
  • For each iteration of while loop, size tells the array how many we want to either add or remove .
  • Finally, we return the value of newArr.

OR

function chunkArrayInGroups(arr, size) {
  let newArr = [];
  for (let i = 0; i < arr.length; i += size) {
    newArr.push(arr.slice(i, i + size));
  }
  return newArr;
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • First, we create an empty array newArr where we will store the groups.
  • The for loop starts at zero, increments by size each time through the loop, and stops when it reaches arr.length.
  • Note that this for loop does not loop through arr. Instead, we are using the loop to generate numbers we can use as indices to slice the array in the right locations.
  • Inside our loop, we create each group using arr.slice(i, i+size), and add this value to newArr with newArr.push(). Finally, we return the value of newArr.

Top comments (0)