Home »
JavaScript »
JavaScript Examples
How to concatenate nested JavaScript arrays?
By IncludeHelp Last updated : January 20, 2024
Nested arrays are arrays that have one or more arrays inside an array like its element. In this tutorial, we will learn how can we concatenate arrays within arrays i.e., nested arrays.
Problem statement
Given two nested JavaScript arrays, we have to concatenate them and store the result in another array.
Concatenating nested arrays
To concatenate nested JavaScript arrays, you can use the Array.concat() method. Call the concat() method with a nested array and pass the other array as a parameter. The result will be a concatenated array of nested arrays.
JavaScript code to concatenate nested arrays
The following example concatenates two nested arrays arr1 and arr2.
// creating two nested arrays
const arr1 = [[1, 2, 3], [4]];
const arr2 = [5, 6, 6, [8, 9]];
// concatenating nested arrays
const result = arr1.concat(arr2);
// printing the arrays
console.log("arr1:", arr1);
console.log("arr2:", arr2);
console.log("result:", result);
Output
The output of the above code is:
arr1: [Array(3), Array(1)]
arr2: [5, 6, 6, Array(2)]
result: [Array(3), Array(1), 5, 6, 6, Array(2)]
To understand the above example, you should have the basic knowledge of the following JavaScript topics: