15 January 2024

Split array to groups of 3. For convenience there are two methods. Both variations achieve the task of splitting an array into groups of three elements in JavaScript. The first variation uses a more traditional for loop to iterate through the original array, slicing it into groups of the specified size and pushing those groups into a new array. On the other hand, the second variation employs the Array.from method to create a new array based on the length of the original array divided by the group size. It then uses an arrow function in the Array.from method to slice the original array into groups of three based on the index. Both variations are valid approaches, and the choice between them may depend on personal coding style preferences or specific requirements of the project.

Source code viewer
  1. // Function, that splits array into groups.
  2. function splitArrayIntoGroups(array, groupSize) {
  3. const groups = [];
  4. for (let i = 0; i < array.length; i += groupSize) {
  5. groups.push(array.slice(i, i + groupSize));
  6. }
  7. return groups;
  8. }
  9. const originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  10. const groupsOfThree = splitArrayIntoGroups(originalArray, 3);
  11. console.log(groupsOfThree);
  12.  
  13. // One-liner, if you want to conserve space.
  14. const originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  15. const groupsOfThree = Array.from({ length: Math.ceil(originalArray.length / 3) }, (_, index) => originalArray.slice(index * 3, index * 3 + 3));
  16. console.log(groupsOfThree);
Programming Language: ECMAScript