Skip to content
Advertisement

How to fill an array with elements from another array of different size? (leaving non existent indexes as zero)

SCENARIO 1: if main array length is < 8

Declaration:

JavaScript

I want to add the values from mainArray into arrayOne, with the spare elements being left as zero.

Desired array:

JavaScript

SCENARIO 2: if main array length is > 8

Declaration:

JavaScript

I want to add the the first 8 values from mainArray into arrayOne, and then the remaining values in arrayTwo, leaving the other indexes as zero (you’ll see the 9 and 10 on the right of the second array, so arrayOne is left to right, arrayTwo is right to left. If there was an arrayThree, that would be left to right again)

Desired arrays:

JavaScript

Advertisement

Answer

Try this.

JavaScript

and

JavaScript

output

JavaScript

Do this if you want to copy to more than two arrays without reversing them.

JavaScript

and

JavaScript

output

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement