# Very best way to concatenate array of arrays, while applying a function

**URL:** <https://discourse.julialang.org/t/very-best-way-to-concatenate-array-of-arrays-while-applying-a-function/88151>\
**Category:** New to Julia\
**Tags:** question\
**Created:** [October 3, 2022, 9:59am UTC](https://discourse.julialang.org/t/very-best-way-to-concatenate-array-of-arrays-while-applying-a-function/88151 "2022-10-03T09:59:44Z")\
**Posts on this page:** 1\
**Showing post:** 11

<div class="post-metadata">

**Author:** ![mcabbott](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mcabbott/32/6603_2.png) [@mcabbott](https://discourse.julialang.org/u/mcabbott)\
**Post date:** [October 4, 2022, 12:20am UTC](https://discourse.julialang.org/t/very-best-way-to-concatenate-array-of-arrays-while-applying-a-function/88151/11 "2022-10-04T00:20:58Z")

</div>

> [@Per](#):
>
> `reduce` can check the sizes beforehand to know how much memory to allocate, but `mapreduce` cannot know the sizes of arrays output by the user function before it is called.

This is true, although it could still do better than pairwise `vcat`, for instance by guessing that all are the same size as the first. Or by repeated doubling like `append!`.

> [@Mason](#):
>
> this will only work if `fun` always returns a vector of the same length

Indeed, this is one of the things which makes `stack` easier.

> [@BambOoxX](#):
>
> Do you know why `mapreduce` cannot hit the same methods than reduce ?

Mostly nobody has got around to it. [PR 31636](https://github.com/JuliaLang/julia/issues/31636) had a go. Another option would simply be to send this to `reduce(vcat, map(f, xs))`, as this will usually be better. (This is also what happens for `mapreduce(f, op, xs, ys)` at present.)

The other option would be to write a `flatten` companion for `stack`, since these clever `reduce` overloads are hard to discover & quite fragile – it’s easy to step off the fast path, as with [init keyword](https://discourse.julialang.org/t/how-can-i-do-list-comprehension-for-vcat/84178/11) for example.

---

_[View the full topic](https://discourse.julialang.org/t/very-best-way-to-concatenate-array-of-arrays-while-applying-a-function/88151)._
