arraysgoogle-apps-scriptgoogle-sheetsrangerows

Fill Down values from a 1x6 array into an _x6 array Google App Script for Google Sheet


I've got this:

array_to_fill_down = [a, b, c, cat, 15, blue]
rows = 3

What I want is this: array_output

[
{a, b, c, cat, 15, blue},
{a, b, c, cat, 15, blue},
{a, b, c, cat, 15, blue}
]

Sorry, I know I'm probably not using the correct symbols. That's part of my problem, I'm sure.

Thanks!


Solution

  • Probably something like this:

    array_to_fill_down = ['a', 'b', 'c', 'cat', 15, 'blue'];
    rows = 3;
    
    var new_array = [];
    while (rows--) new_array.push(array_to_fill_down)
    

    Or

    var new_array = new Array(rows).fill(array_to_fill_down);
    

    Not sure if I understand your goal, though.


    Update

    The code above creates the references on the original array. Say, if you change one element of the original array it will change every row of the new array. It causes the nasty errors pretty often. If you want to have genuine independent copies instead of references it can be done this way:

    array_to_fill_down = ['a', 'b', 'c', 'cat', 15, 'blue'];
    rows = 3;
    
    var new_array = [];
    while (rows--) new_array.push(array_to_fill_down.slice()); // <-- HERE
    

    The second one-liner with Array.fill() method can't do it.