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.ts235 chars11 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.ts143 chars4 lines
gistlibby LogSnag