Flattening arrays of objects

Starting from the previous example we are going to flatten arrays of objects with 3 method:

  • map with join
  • forEach with concat
  • forEach with push


We are trying to do it in a functional way, clearer and shorter. The more (nested) elements you have, the better the map option will be versus forEach with concat. If we are looking for the fastest option, a classical for with push will be the best one as JapanFever said and the worst a forEach with concat.

Just launch these basic test I made in jsPerf and try yourself:

https://jsperf.com/map-with-join-vs-foreach-with-concat

https://jsperf.com/flattening-arrays-of-objects

The more (nested) elements you have, the more equal the forEach will be comparing with the classical for.

JavaScript engines performance are improving constantly and I hope to see a better way to flatten using map xD

 

2 replies
  1. japanfever
    japanfever says:

    forEach is fast, but concat is slow. The faster will be a classic for:

    array = []; /*E3839EE383AAE382AAE9B3A9E38388E383ACE383AD*/
    for (var a = 0; a < alphas.length; a++) {
    for (var g = 0; g < alphas[a].gammas.length; g++) {
    for (var x = 0; x < alphas[a].gammas[g].betas.length; x++) {
    array.push(alphas[a].gammas[g].betas[x]);
    }
    }
    }

    ¯\_(ツ)_/¯

    • Génesis
      Génesis says:

      Yeah JapanFever, concat in this case is piece of s*, it wasn’t made for that. I have added the classical for on jsPerf.

      The more (nested) elements you have, the more equal the forEach will be comparing with the classical for.
      See how complex it becomes in the performance path: https://jsperf.com/flattening-arrays-of-objects
      JavaScript engines performance are improving constantly (thankfully) and I hope to see a better way to flatten using map xD
      I think, I will stay with map with a small bunch of elements and most of the cases with forEach with push.
      Thank you for your answer!

Comments are closed.