# Javascript reducing an array of arrays to a single array with concat or push

Which is more efficient? (Both memory usage and speed.)

arrayOfArrays.reduce((acc, innerArray) => {
acc.push(...innerArray);
return acc;
}, []);


Or

arrayOfArrays.reduce((acc, innerArray) => acc.concat(innerArray), []);


The first one is more efficient in a sense that you're just reusing the array, and not recreating one on each iteration like the other one. However, neither of them are "efficient" in a sense that you're still looping... and there's actually a better way.

array.concat accepts multiple args. You can just use the spread operator to spread the arrays in the array as its args.

const arr = Array.prototype.concat.call([], ...arrayOfArrays)


Or the older way to do it is using function.apply

const arr = Array.prototype.concat.apply([], arrayOfArrays)


I'm being too formal and all. A shorter version of the spread looks like:

const arr = [].concat(...arrayOfArrays)


const arrayOfArrays = [[1,2], [3, 4], [5, 6]]
const arr1 = Array.prototype.concat.call([], ...arrayOfArrays)
const arr2 = Array.prototype.concat.apply([], arrayOfArrays)
const arr3 = [].concat(...arrayOfArrays)

console.log(arr1)
console.log(arr2)
console.log(arr3)

• you've given lots of answers but haven't really explained which is most efficient – I wrestled a bear once. Aug 11 '17 at 13:14
• Based on my simple tests in my browser on my computer, the first example given here using concat.call is consistently and significantly slower than the OP's original code. The other two examples seems to be more or less the same level of efficiency, but the last one using just concat and a spread did sometimes execute a few milliseconds faster. Conclusion: do anything but the first example in this answer. – I wrestled a bear once. Aug 11 '17 at 13:37
• @Iwrestledabearonce. This is a case of microbenchmarking and premature optimization. I would rather make code concise, readable and do less things than worry about milliseconds difference. Also native APIs over time will become faster as vendors optimize code, which equates to less work on your part. "Efficiency" is relative. If your code is efficient, but took you days to make it and prove that it's faster, that's not efficient. – Joseph Aug 11 '17 at 14:15
• @Josephi fully agree and I've upvoted your answer instead of attempting to write a competing one, however the user was asking specifically about efficiency rather than readability or maintainability. I also made a point to note that these were the results I got on one specific browser. Mileage may vary. – I wrestled a bear once. Aug 11 '17 at 14:19
• @Iwrestledabearonce. Actually, a competing answer does sound nice. :D – Joseph Aug 11 '17 at 14:42