← coderrocketfuel.com

How to Combine Two Arrays in Node.js

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:

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:

[ "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:

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:

[ "Arbys", "McDonalds", "Wendys", "Taco Bell", "Chick-fil-A" ]

There you have it! Two ways to combine two arrays in Node.js.