Skip to content

Instantly share code, notes, and snippets.

@jeanbenitez
Created May 7, 2019 15:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeanbenitez/5944c392538b6955936622386192cf65 to your computer and use it in GitHub Desktop.
Save jeanbenitez/5944c392538b6955936622386192cf65 to your computer and use it in GitHub Desktop.
Simple array to matrix algorithm with Typescript
/**
* Convert simple array into two-dimensional array (matrix)
*
* @param list The array
* @param width The num of elements per sub-array
* @return the new matrix
*/
export const listToMatrix = <T>(list: T[], width: number): T[][] => {
const matrix = [];
for (let i = 0, k = -1; i < list.length; i++) {
if (i % width === 0) {
k++;
matrix[k] = [];
}
matrix[k].push(list[i]);
}
return matrix;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment