Code Logo

Merge with Spread Operator

Published at25 Jul 2026
JavaScript Data Structures Easy 0 views
Like0

Write a JavaScript function that takes two arrays and returns a single merged array using the spread operator (...). The spread operator expands an iterable into its individual elements, allowing you to combine arrays concisely without using concat or loops.

To merge two arrays arr1 and arr2 using spread, create a new array containing the spread elements of both arrays: [...arr1, ...arr2]. The spread operator pulls each element from the source array and places them into the new array in order. This creates a shallow copy of both arrays.

The spread operator was introduced in ES6 and has become the standard way to merge arrays in modern JavaScript. It is more readable and expressive than concat() and avoids mutation of the original arrays. The spread operator works with any iterable including arrays, strings, and Sets.

Time complexity is O(n + m) where n and m are the lengths of the two arrays. The spread operator iterates through each element of both arrays to create the new array. Space complexity is O(n + m) for the result array.

Edge cases include empty arrays (spreading an empty array produces no elements), arrays with different types of elements, and ensuring the original arrays remain unmodified after the operation.

Example Input & Output

Example 1
Input
[1,2,3],[4,5,6]
Output
[1,2,3,4,5,6]
Explanation

Merge longer arrays

Example 2
Input
[1,2],[3,4]
Output
[1,2,3,4]
Explanation

Merge two arrays using spread

Example 3
Input
[],[5,6]
Output
[5,6]
Explanation

First array empty

Example 4
Input
[7],[8]
Output
[7,8]
Explanation

Both single elements

Example 5
Input
[1,2],[]
Output
[1,2]
Explanation

Second array empty

Algorithm Flow

Recommendation Algorithm Flow for Merge with Spread Operator
Recommendation Algorithm Flow for Merge with Spread Operator

Solution Approach

Merge two arrays using the spread operator (...) which expands each array into individual elements within a new array literal. This syntax provides a concise, readable way to combine arrays.

function solution(a, b) {
  return [...a, ...b];
}

The spread operator was introduced in ES6 and works with any iterable, not just arrays. Like concat(), it creates a shallow copy. It can also be used for cloning arrays with [...arr] and for passing array elements as function arguments.

Time complexity is O(n+m), space complexity is O(n+m).

Best Answers

javascript - Approach 1
function solution(arr1, arr2) {
  return [...arr1, ...arr2];
}