In JavaScript, when we want to combine two or more arrays into one new array, we can use the method called concat
. This method is much more efficient and simpler compared to older methods.
The issue of combining arrays in programming is always one of the essential needs. Assume you have two lists of data that you want to turn into a single unified list. This is where concat
comes to aid and can simplify the problem quickly.
The nice thing about using concat
is that it does not change the existing arrays and only produces a new array that includes each input array. This unique feature can significantly assist in keeping your code clean and readable.
Let’s allow ourselves to examine an example to see how this function operates. Assume we have two arrays arr1
and arr2
and we want to combine them.
Using this method is straightforward, as follows:
<script>
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const resultArray = arr1.concat(arr2);
console.log(resultArray); // [1, 2, 3, 4, 5, 6]
</script>
const arr1 = [1, 2, 3];
This defines the first array under the name arr1
which consists of several numbers.
const arr2 = [4, 5, 6];
This defines the second array named arr2
that contains different numbers.
const resultArray = arr1.concat(arr2);
Using the concat
method to merge the arrays and create a new array named resultArray
.
console.log(resultArray);
This outputs the result of combining the arrays which is a combined set from the two input arrays.