I have 3 inputs: an array, a total count integer and an arbitrary value.
input_array = ['hello', 'there', 'world']
total_count = 15
fill_value = null
Desired output:
output = [
'hello',
null,
null,
null,
null,
'there',
null,
null,
null,
null,
'world',
null,
null,
null,
null,
]
Assume that the length of input_array
does not exceed total_count
. Other scenarios:
- If
total_count
was3
, you’d get['hello', 'there', 'world']
- If
total_count
was4
, you’d get['hello', null, 'there', 'world']
- etc. etc.
This feels like a candidate for a recursive function? You could take Math.ceil((total_count - input_array.length) / input_array.length)
and use that value to fill in the slots but I’m not sure what the cleanest syntax would look like.
2
Answers
You can use
Array#flatMap
to construct the final array.The trick is figuring out where the items go. If the number of elements does not fit the output array evenly, every index will be pushed right by one for each previous item to evenly distribute the overhead: