Code Logo

Merge Arrays with concat()

Published at25 Jul 2026
JavaScript Collections Easy 0 views
Like0

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

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

Merge two arrays

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

Second array empty

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

First array empty

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

Another merge

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

Different sizes

Algorithm Flow

Recommendation Algorithm Flow for Merge Arrays with concat()
Recommendation Algorithm Flow for Merge Arrays with concat()

Solution Approach

function solution(arr1, arr2) {
  return arr1.concat(arr2);
}

Best Answers

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