split array into groups of 3 in javascript

To split an array into groups of three in JavaScript, you can loop through the array and use the slice() method to extract a portion of the array. Here's an example:

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

const groupsOfThree = [];

for (let i = 0; i < arr.length; i += 3) {
  const group = arr.slice(i, i + 3);
  groupsOfThree.push(group);
}

console.log(groupsOfThree); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
245 chars
11 lines

In the above code, we start by declaring an array arr containing the original array. We then declare an empty array called groupsOfThree that we will use to store our groups of three.

We then loop through the arr array using a for loop, incrementing by three at each iteration (because we want groups of three).

Inside the loop, we use the slice() method on arr to extract a portion of the array containing the current group of three elements. We then push this group to the groupsOfThree array.

Finally, we log the groupsOfThree array to the console, which will output [[1, 2, 3], [4, 5, 6], [7, 8, 9]] in this case.

gistlibby LogSnag