split array into groups of 3 in typescript

To split an array into groups of three in TypeScript, you can use the reduce() method to iterate over the array and create a new array of sub-arrays with a length of 3. Here's an example function that does this:

index.ts
function splitIntoGroupsOfThree<T>(arr: T[]): T[][] {
  return arr.reduce<T[][]>((acc, val, i) => {
    const idx = Math.floor(i / 3);
    if (!acc[idx]) {
      acc[idx] = [];
    }
    acc[idx].push(val);
    return acc;
  }, []);
}
235 chars
11 lines

Here, the reduce() method takes two arguments: the accumulator (acc) and the current element of the array (val). The accumulator is initialized with an empty array ([]), and on each iteration, the function checks whether the current index is a multiple of 3. If it is, it creates a new sub-array (acc[idx] = [];) and pushes the current element to it (acc[idx].push(val);). Finally, it returns the accumulator. This way, the reduce function returns an array of sub-arrays with the length of 3.

You can then use this function like this:

index.ts
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const groups = splitIntoGroupsOfThree(arr);
console.log(groups); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
143 chars
4 lines

gistlibby LogSnag