Common Spread Array Patterns
You'll learn practical, real-world patterns using spread that solve everyday array manipulation problems.
Now that you understand spread fundamentals, let's explore three patterns you'll use constantly in production code.
Removing Duplicates
Combine spread with Set to eliminate duplicate values:
const numbers = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4, 5]
Set automatically keeps only unique values, and spread converts it back to an array. Think of Set as a bouncer that only lets each guest in once.
Flattening One Level
Spread can flatten nested arrays by one level:
const nested = [[1, 2], [3, 4], [5]];
const flattened = [].concat(...nested);
console.log(flattened); // [1, 2, 3, 4, 5]
Each sub-array spreads into concat(), merging them all together. Note: this only works for one level deep—deeply nested arrays need .flat().
Conditional Insertion
Use spread with conditionals to add elements only when needed:
const baseItems = ['apple', 'banana'];
const includeExtra = true;
const items = [
...baseItems,
...(includeExtra ? ['cherry', 'date'] : [])
];
console.log(items); // ['apple', 'banana', 'cherry', 'date']
If includeExtra is false, you spread an empty array (adding nothing). This keeps your array building clean without if blocks or .push() calls.
These patterns appear everywhere: deduplicating API responses, merging configuration arrays, building dynamic lists based on user permissions.
Key Takeaway: Spread shines in common patterns like removing duplicates with Set, flattening one level with concat(), and conditionally inserting elements using ternary operators—making array manipulation more declarative and readable.