Combine Two or More Arrays in JavaScript
Combining arrays is one of the most common tasks in JavaScript. Whether you're merging user data, stacking results, or simply uniting two sets of items like fruits and vegetables — being able to fluently combine arrays unlocks the power of data manipulation. JavaScript offers more than one way to combine arrays, and each has its use cases. Let’s explore them with real, digestible examples.
Method 1: Using concat()
Method
The concat()
method is a built-in JavaScript function that joins two or more arrays and returns a new array without changing the existing ones. It is simple, intuitive, and perfect for combining multiple arrays in a single go.
const fruits = ["apple", "banana", "cherry"];
const vegetables = ["carrot", "lettuce", "spinach"];
const groceries = fruits.concat(vegetables);
console.log(groceries);
["apple", "banana", "cherry", "carrot", "lettuce", "spinach"]
Method 2: Using the Spread Operator (...
)
The spread operator offers a modern, flexible way to combine arrays. Introduced in ES6, it “spreads” the elements of each array into a new array. This syntax is clean and works beautifully for merging multiple arrays — not just two!
const fruits = ["apple", "banana"];
const vegetables = ["carrot", "lettuce"];
const snacks = ["chips", "cookies"];
const shoppingList = [...fruits, ...vegetables, ...snacks];
console.log(shoppingList);
["apple", "banana", "carrot", "lettuce", "chips", "cookies"]
Method 3: Using a Loop (Manual Merge)
Though less elegant, you can always use a for
loop to manually add items from one array to another. This gives you more control over how items are inserted, filtered, or transformed during the merge process.
const arr1 = ["Item 1", "Item 2"];
const arr2 = ["Item 3", "Item 4"];
let result = [];
for (let item of arr1) {
result.push(item);
}
for (let item of arr2) {
result.push(item);
}
console.log(result);
["Item 1", "Item 2", "Item 3", "Item 4"]
Final Thoughts
Choosing the right way to combine arrays depends on what you’re building. If simplicity and readability are your priorities, go with concat()
or the spread operator. If you're preparing data conditionally or inserting complex logic during the merge, loops give you that flexibility.
Comments
Loading comments...