Home

Published

- 1 min read

typescript array to matrix

img of typescript array to matrix

The solution for this is noted below

typescript array to matrix

Solution

   // untyped
export const matrixify = (arr, size) =>
	Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
		arr.slice(i * size, i * size + size)
	)

// typed
export const toMatrix = <T>(arr: Array<keyof T>, size: number): (keyof T)[][] => {
	return Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => {
		return arr.slice(i * size, i * size + size)
	})
}

Try other methods by searching on the site. That is if this doesn’t work