Max subarray length which sum not bigger than the main array length
Possible sub-arrays for [1, 2, 3, 4]
[1],
[2], [1, 2],
[3], [1, 3], [2, 3], [1, 2, 3],
[4], [1, 4], [2, 4], [1, 2, 4], [3, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]
Possible sub-arrays for [1, 2, 3, 4]
[1],
[2], [1, 2],
[3], [1, 3], [2, 3], [1, 2, 3],
[4], [1, 4], [2, 4], [1, 2, 4], [3, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]
Using an array to keep track of where we came from. Try it, click the right top buttons to navigate and check the backward arrow, any time you go to the Main page the tracking will be reseted.
Starting from the previous example we are going to flatten arrays of objects with 3 method:
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