Merge Arrays with concat()
Write a JavaScript function that takes two arrays and returns a new array containing all elements from both arrays using Array.concat(). The concat() method creates a new array by merging the existing arrays without modifying the source arrays.
Array.prototype.concat() is a JavaScript method that combines two or more arrays. It returns a new array containing the elements of the calling array followed by the elements of the arguments. Concat can accept multiple arrays or individual values: arr1.concat(arr2, arr3) or arr1.concat(1, 2, 3).
Unlike the spread operator which was introduced in ES6, concat() has been available since ES3 and works in all JavaScript environments. Concat creates a shallow copy of the elements, meaning nested objects are copied by reference, not by value. This is suitable for arrays of primitives but requires caution with reference types.
Time complexity is O(n + m) where n and m are the lengths of the arrays. Space complexity is O(n + m) for the new array. The original arrays remain unchanged.
Edge cases include empty arrays (concatenating with empty returns a copy of the other array), single-element arrays, concatenating with non-array values (they are added as individual elements), and ensuring both input arrays are preserved.
Example Input & Output
Merge two arrays
Second array empty
First array empty
Another merge
Different sizes
Algorithm Flow
Solution Approach
Merge two or more arrays into a new array without modifying the originals using concat(). This method accepts any number of array or value arguments and returns a new combined array.
concat() creates a shallow copy, meaning nested arrays and objects are still referenced rather than cloned. The spread operator [...a, ...b] achieves the same result and is often preferred in modern JavaScript for its syntax clarity.
Time complexity is O(n+m), space complexity is O(n+m).
Best Answers
function solution(arr1, arr2) {
return arr1.concat(arr2);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
