Created
June 17, 2025 20:27
-
-
Save topherPedersen/bbf5efedf19e9700a9a7f6eaaf5f4093 to your computer and use it in GitHub Desktop.
Create an Array of Arrays (Rows) From One Flat Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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