Merging arrays is a common task in JavaScript development. Learn to combine multiple arrays into a single array. With several ways to achieve this, they each have their own use case and benefit. Straightforward ways of doing so involve using the concat
method, the spread operator, or utility libraries like Lodash.
Snippets
Using concat
Method
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = array1.concat(array2);
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
The concat
method is a built-in JavaScript function that merges two or more arrays into a new array without modifying the original arrays.
Using the Spread Operator
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
The spread operator (...
) provides a concise and modern way to merge arrays by spreading the elements of each array into a new array.
Using Lodash _.concat
const _ = require('lodash');
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = _.concat(array1, array2);
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
Lodash is a popular utility library that provides a _.concat
method to merge arrays. This method is useful when you are already using Lodash in your project and prefer a consistent API.
Article continues below
So I know our tutorials are totally awesome 😉. But maybe, going through how-to's is not how you would like to be spending your precious time. Imagine a world where things just work. Kinsta's hosting platform gets our official -"Easy Way of the Day" seal. Advanced features that are incredibly easy to set up.
- Cloudflare integration
- Automatic daily backups
- DDoS protection
- Exclusively for WordPress
Footnotes: