Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created June 17, 2025 20:27
Show Gist options
  • Save topherPedersen/bbf5efedf19e9700a9a7f6eaaf5f4093 to your computer and use it in GitHub Desktop.
Save topherPedersen/bbf5efedf19e9700a9a7f6eaaf5f4093 to your computer and use it in GitHub Desktop.
Create an Array of Arrays (Rows) From One Flat Array
const createRowsFromArray = (flatArray: string[]): string[][] => {
const remainder = flatArray.length % 2;
for (let i = 0; i < flatArray.length - 1; i = i + 2) {
console.log(`${flatArray[i]} | ${flatArray[i + 1]}`);
}
if (remainder) {
console.log(flatArray[flatArray.length - 1]);
}
return [
['foo', 'bar', 'baz'],
['foo', 'bar', 'baz'],
['foo', 'bar', 'baz'],
];
};
// red, orange, yellow, green, blue, indigo, and violet
const flatArrayOfSix = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo'];
const flatArrayOfSeven = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
createRowsFromArray(flatArrayOfSix);
console.log('');
console.log('');
console.log('');
createRowsFromArray(flatArrayOfSeven);
console.log('');
console.log('');
console.log('');
createRowsFromArray(['red', 'orange']);
console.log('');
console.log('');
console.log('');
createRowsFromArray(['red']);
console.log('');
console.log('');
console.log('');
createRowsFromArray([]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment