How to fill a large array by repeatedly copying the values from a small array in TypeScript

1 Answer

0 votes
// Initialize the small and large arrays
const smallArray = [1, 2, 3, 4, 5];
const largeArray = new Array(30).fill(0);

const largeLen = largeArray.length;
const smallLen = smallArray.length;

// Fill largeArray with elements from smallArray using the modulo operator
for (let i = 0; i < largeLen; i++) {
    largeArray[i] = smallArray[i % smallLen];
}

console.log(largeArray.join(" "));



/*
run:

"1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5"

*/

 



answered Feb 8, 2025 by avibootz
...