Merge with Spread Operator
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
Merge longer arrays
Merge two arrays using spread
First array empty
Both single elements
Second array empty
Algorithm Flow

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.
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
function solution(arr1, arr2) {
return [...arr1, ...arr2];
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
