Home  >  Article  >  Web Front-end  >  How do you combine multiple arrays into a single new array in JavaScript?

How do you combine multiple arrays into a single new array in JavaScript?

DDD
DDDOriginal
2024-11-16 11:36:02747browse

How do you combine multiple arrays into a single new array in JavaScript?

Combining Array Items into a New Array

In JavaScript, you may encounter situations where you need to consolidate the elements of multiple arrays into a single new array. While iterating over each individual array and manually adding items one by one is an option, this approach can be tedious and error-prone. Fortunately, JavaScript provides a more efficient solution.

Leveraging the concat Function

The concat function offers a concise way to combine the contents of multiple arrays. Simply pass the arrays to be concatenated as arguments to the function, and it will return a new array containing all the elements in sequence. For example:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);

The value of newArray will be [1, 2, 3, 4], with arrayA and arrayB remaining unchanged. The concat function operates on a copy of the input arrays, ensuring that the originals stay intact.

The above is the detailed content of How do you combine multiple arrays into a single new array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn