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

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
for (let i = 0; i < largeLen; i++) {
    largeArray[i] = smallArray[i % smallLen];
}

// print 1
for (let i = 0; i < largeLen; i++) {
    process.stdout.write(largeArray[i] + " ");
}

console.log();

// print 2
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 
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
edited Feb 8, 2025 by avibootz
...