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
JavaScript HTML// map with join vs forEach with concat
let array = [];
// Returns an array of n elements filled with content
let get_array = (n, content) => Array(n).fill(content);
// Returns an object with a name property that has a content value
let get_object = (name, content) => Object.defineProperty({}, name, {
value: content
})
// 3 levels of arrays with objects (nested)
let alphas =
get_array(3, get_object('gammas',
get_array(2, get_object('betas',
get_array(1, 'stuff')
))
));
// join
array = alphas.map(a =>
a.gammas.map(g => g.betas)
).join();
document.querySelector('#join').textContent = array;
// concat
array = [];
alphas.forEach(a =>
a.gammas.forEach(g => {
array = array.concat(g.betas);
})
);
document.querySelector('#concat').textContent = array;
// push
array = [];
alphas.forEach(a =>
a.gammas.forEach(g => {
g.betas.forEach(b => array.push(b));
})
);
document.querySelector('#push').textContent = array;
<div id="join"></div>
<div id="concat"></div>
<div id="push"></div>
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