How to Combine Two Arrays in NodeJS
Introduction
Are you trying to figure out how to combine two arrays using Node.js?
There are two ways to do it. The modern technique is to use the ES6 spread operator like this: [...firstArray, ...secondArray]. And the second technique is to use the concat() method like this: firstArray.concat(secondArray).
Let's run through a quick code example for each.
Table of Contents
ES6 Spread Operator
Spread syntax allows an iterable like an array or string to be expanded in places where an N number of arguments (function calls) or elements (array literals) are expected. And it is commonly used in places where you want to use the elements of an array as arguments to a function.
Here's an example of how you'd use it in your code:
Node.js
 
const firstArray = ["Arbys", "McDonalds", "Wendys"]
const secondArray = ["Taco Bell", "Chick-fil-A"]
 
const combined = [...firstArray, ...secondArray]
If you log the combined variable, one array with all the values combined will be logged:
Output
 
[ "Arbys", "McDonalds", "Wendys", "Taco Bell", "Chick-fil-A" ]
In the next section, we'll show a second method of using concat().
Concat()
The concat() method is used to merge two or more arrays and is built directly into the Node.js language. It doesn't change anything about the existing arrays and just simply combines them into one new array.
Here's a full example of the concat() method:
Node.js
 
const firstArray = ["Arbys", "McDonalds", "Wendys"]
const secondArray = ["Taco Bell", "Chick-fil-A"]
 
const combined = firstArray.concat(secondArray)
If you log the combined variable, one array with all the values combined will be logged just like the last example:
Output
 
[ 'Arbys', 'McDonalds', 'Wendys', 'Taco Bell', 'Chick-fil-A' ]
Conclusion
There you have it! Two ways to combine two arrays in Node.js.
Thanks for reading and happy coding!
Have any questions or comments about this article? You can contact me via email at nick@coderrocketfuel.com or on Twitter at @CoderRocketFuel.
If you enjoyed this free content, please consider supporting what I do by Buying Me a Coffee.