Categories
JavaScript Answers

How to Join or Combine Two JavaScript Arrays by Concatenating Them into One Array?

Spread the love

Sometimes, we want to combine 2 JavaScript arrays by concatenating them into one array.

In this article, we’ll look at how to join or combine 2 JavaScript arrays by concatenating them into one array.

Use the Array.prototype.concat Method

One way to join 2 Javascript arrays by concatenating them into one array is to use the JavaScript array’s concat method.

For instance, we can write:

const a = ['a', 'b', 'c'];
const b = ['d', 'e', 'f'];
const c = a.concat(b);
console.log(c)

We call a.concat(b) to add the entries of b after the entries of a and return the new array with all the entries.

Therefore, c is:

["a", "b", "c", "d", "e", "f"]

Use the Spread Operator

Another way to combine 2 arrays by joining them together is to use the spread operator.

For example, we can write:

const a = ['a', 'b', 'c'];
const b = ['d', 'e', 'f'];
const c = [...a, ...b]
console.log(c)

We spread the entries of a and b into a new array to form the c array.

They’ll be spread in the same order that they’re listed.

Therefore, c is now:

["a", "b", "c", "d", "e", "f"]

Conclusion

We can use the JavaScript array’s concat method or the spread operator to combine 2 JavaScript arrays by joining them together.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *