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"]]
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;
}
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)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)