Course contentsShow
← JavaScript
Lesson 993 of 2,72322. Spread and RestFree lesson

Merging Multiple Arrays

Combine arrays with spread syntax, exploring how order and duplicates are handled.

Merging Multiple Arrays

You'll learn how to combine multiple arrays into one using the spread operator, and understand how order and duplicates are handled.

When you need to join several arrays into a single array, the spread operator (...) provides a clean, readable way to do it. You simply spread each array inside a new array literal, and JavaScript concatenates them in the order you specify.

How It Works

Think of spreading arrays like emptying boxes of items into one larger container—each box's contents spill out in order, and everything ends up in the final container exactly as you arranged them.

const fruits = ['apple', 'banana'];
const veggies = ['carrot', 'broccoli'];
const grains = ['rice', 'wheat'];

const allFoods = [...fruits, ...veggies, ...grains];
console.log(allFoods);
// ['apple', 'banana', 'carrot', 'broccoli', 'rice', 'wheat']

Order Matters

The arrays merge in the exact order you spread them:

const first = [1, 2];
const second = [3, 4];

const merged1 = [...first, ...second];  // [1, 2, 3, 4]
const merged2 = [...second, ...first];  // [3, 4, 1, 2]

Duplicates Are Preserved

Spread doesn't remove duplicates—if elements appear in multiple arrays, they all end up in the result:

const a = [1, 2, 3];
const b = [2, 3, 4];

const combined = [...a, ...b];
// [1, 2, 3, 2, 3, 4] — the duplicates remain!

You can even mix arrays with individual elements:

const nums = [1, 2];
const more = [...nums, 3, 4, ...[5, 6]];
// [1, 2, 3, 4, 5, 6]

Key Takeaway: Use spread syntax to merge multiple arrays by placing ...array inside a new array literal—order is preserved, and duplicates are kept.