How to get a modified array with or without spread syntax in this case?

Viewed 42

How to simplify and improve the code below?

The code below works as expected if myarr.length === 2:

[...myarr[0].arrk.map(myfunc), ...myarr[1].arrk.map(myfunc), ...myarr[2].arrk.map(myfunc)]

How to modify the code above so that myarrarray could be any length so that the code above works for any length, not just for 2? It should be all, not 2.

P.S. I believe the solution

myarr.map(a => a.arrk.map(myfunc))

is too close to the correct answer, but not exactly: it returns [Array(1), Array(2)], but not the elements.

Thank you.

1 Answers

You may try that with Array.prototype.flatMap():

myarr.flatMap(({arrk}) => arrk.map(myfunc))

Or, if .flatMap() is not available in your environment, the same thing with Array.prototype.reduce():

myarr.reduce((acc, {arrk}) => (acc.push(...arrk.map(myfunc)), acc), [])
Related