Back to Home
Arrays

How to Copy and Merge Arrays

Use spread operator (...) to copy and concatenate arrays

Quick Answer (2024 ES6+ Way)

javascript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]

Live Example

javascript
const fruits = ['apple', 'banana'];
const vegetables = ['carrot', 'lettuce'];
const more = ['cheese', 'bread'];

const groceries = [...fruits, ...vegetables, ...more];
console.log(groceries);

// Add items at different positions
const withExtra = ['start', ...fruits, 'middle', ...vegetables];
console.log(withExtra);

Common Variations

Remove Duplicates
javascript
const unique = [...new Set([1, 2, 2, 3, 3, 4])];
// [1, 2, 3, 4]
Add to Array Immutably
javascript
const newArr = [...oldArr, newItem];
const withInsert = [...arr.slice(0, 2), newItem, ...arr.slice(2)];

❌ Don't Do This (Outdated Way)

Avoid .concat() or manual loops

javascript
// DON'T DO THIS
var combined = arr1.concat(arr2);

Browser Support

Works in all modern browsers (ES2015+)

#spread#array#copy