When you engage with JavaScript, you will frequently encounter the task of managing arrays and collections of values held within a single variable. A typical requirement is to merge two or more arrays into a single, larger array. The concat method is specifically designed to assist you in achieving this.
In this article, we will explain the functionality of concat in a straightforward manner, making it accessible for beginners who are just beginning their programming journey.
What is the concat Method?
The concat function is a native method in JavaScript that is associated with the Array object. Its primary purpose is to combine two or more arrays into a single, new array.
The term "concat" is an abbreviation of "concatenation," which refers to the process of joining items together in a sequential manner or a series.
For instance,
- The process of concatenating strings involves merging multiple strings together.
- The act of concatenating arrays refers to the combination of arrays into one.
Basic Syntax
let newArray = array1.concat (array2, array3, …);
- array1 is the original array you call concat
- array2 , array3 , etc., are other arrays or values you want to add.
- The newArray is a result that combines all these arrays.
How does concat work with arrays?
The concat function is utilized with arrays to merge two or more arrays (or even standalone values) into a fresh, single array.
Below is a detailed breakdown of the operational process:
1. Starting with the original array
When you invoke the concat method on an already established array, that particular array is referred to as the base. For illustration, let's take the 'fruits' array as our base example.
let fruits = ["apple", "banana"];
2. Passing arrays or values to combine
Within the parentheses of the concat method, you specify the arrays or individual values that you wish to append to the original array.
let vegetables = ["carrot", "tomato"];
let combined = fruits.concat(vegetables);
3. Creating a new array
When merging two arrays using the concat method, the original arrays remain unaltered. Rather, this method generates an entirely new array that begins with the elements from the initial array and subsequently appends all the items you provide to the concat function.
Code:
Example
console.log(combined);
console.log(fruits);
console.log(vegetables);
Output:
[ 'apple', 'banana', 'carrot', 'tomato' ]
[ 'apple', 'banana' ]
[ 'carrot', 'tomato' ]
The arrays containing fruits and vegetables remain intact, while the merged array contains the newly consolidated array.
Examples of Array concat Method
1. Concatenating two arrays
In this instance, we will merge two arrays by employing the concat method.
Code:
Example
const array1 = [1, 2];
const array2 = [3, 4];
const result = array1.concat(array2);
console.log(result);
Output:
[ 1, 2, 3, 4 ]
Explanation:
In the code presented above, there exist two arrays, referred to as array1 and array2. We have utilized the concat method to merge these two arrays into a single array, which we have designated as result. Subsequently, we output this combined array to the console through the use of the console.log method.
2. Concatenating more than two arrays
In this example, we will combine multiple arrays using the concat method.
Code:
Example
const a = [1, 2];
const b = [3, 4];
const c = [5, 6];
const result = a.concat(b, c);
console.log(result);
Output:
[ 1, 2, 3, 4, 5, 6 ]
Explanation:
In the code provided above, there are three arrays identified as a, b, and c. We have merged these arrays utilizing the concat method and assigned the outcome to a new array called result, which we then output to the console.
3. Concatenating arrays by passing values and other arrays
In this example, we will merge an array with separate values along with another array.
Code:
Example
const nums = [10, 20];
const result = nums.concat(30, [40, 50]);
console.log(result);
Output:
[ 10, 20, 30, 40, 50]
Explanation:
In the code provided, there exists an array referred to as nums. This array is merged with the singular value 30 and an additional array containing the elements [40, 50] through the utilization of the concat method. The outcome of this operation is then displayed in the console.
4. Concatenating Nested Arrays
When an array is not flattened:
The concat method, by default, does not perform flattening on nested arrays. In the following example, we will merge an array with a nested array, demonstrating that the output does not result in a flattened array.
Code:
Example
const numbers = [1, 2];
const nestedNumbers = [[3, 4]];
const result = nested.concat(nestedArray);
console.log(result);
Output:
[ 1, 2, [ 3, 4 ] ]
Explanation:
In the code provided above, there are two arrays: the first array is referred to as numbers, while the second one is called nestedNumbers. We have merged these two arrays and saved the combined result in a new array named result, which we then printed to the console. It is evident that the resulting array remains unflattened.
When an array is flattened :
In this example, we will merge an array with a nested array, employing the flat function to ensure that the resulting array is flattened.
Code:
Example
const nested = [1, 2];
const deep = [[3, 4]];
const result = nested.concat(deep);
console.log(result.flat());
Output:
[ 1, 2, 3, 4 ]
Explanation:
This code mirrors the previous example; however, the distinction lies in the fact that the array contained in the result variable is flattened utilizing the flat function.
5. Concatenating with an empty array
In this instance, we will merge an array with an empty array. This process is utilized to generate a duplicate of an existing array.
Code:
Example
const arr = [5, 6];
const result = [].concat(arr);
console.log(result);
Output:
[5, 6]
Explanation:
In the code provided, there exists an array referred to as arr. This array has been merged with an empty array through the use of the concat method, which results in no modifications to the original array. When we output it to the console, the result remains identical to that of the initial array.
When should you use array.concat in JavaScript?
The concat function is incredibly useful when you need to merge arrays or append elements to an array in a straightforward and secure manner. This method is particularly beneficial in cases where you wish to preserve the integrity of the original arrays without modifying them. Below are some scenarios in which employing the concat method is advisable:
1. When you want to combine two or more arrays
When you possess several arrays and wish to combine all of their elements into a single large array, the concat method is the ideal choice. It is significantly more straightforward and neater than implementing loops or employing the push method to insert items individually.
Code:
Example
let fruits = ["apple", "banana"];
let vegetables = ["carrot", "tomato"];
let food = fruits.concat (vegetables);
console.log (food);
Output:
[ 'apple', 'banana', 'carrot', 'tomato' ]
Explanation:
In the code provided, there are two arrays named fruits and vegetables. We utilized the concat method to merge these arrays into a new array referred to as food. Subsequently, we displayed this array in the console.
2. When you want to add new values to an array
The concat method allows you to append single elements or complete arrays of elements to an existing array, all while keeping the original array unchanged.
Code:
Example
let numbers = [1, 2];
let newNumbers = numbers.concat (3, 4, [5, 6]);
console.log (newNumbers);
Output:
[ 1, 2, 3, 4, 5, 6 ]
Explanation:
In the code presented above, there exists an array referred to as numbers. We have merged this array with another array containing the values (3, 4 [5, 6]) utilizing the concat method and assigned the result to a new array called newNumbers. Subsequently, we have output this new array to the console.
3. When you want to avoid changing the original array
In contrast to functions like push or splice, which alter the original array, the concat method does not modify the original array; instead, it generates a completely new array. This characteristic is particularly beneficial in functional programming paradigms or within frameworks such as React, where maintaining immutability is crucial and there is a preference to avoid changing the original data.
Code:
Example
let a = [1, 2];
let b = a.concat (3, 4);
console.log (a);
console.log (b);
Output:
[ 1, 2 ]
[ 1, 2, 3, 4 ]
Explanation:
In the code provided, there exists an array referred to as a. We have merged it with an additional array containing the elements (3, 4) utilizing the concat method. The result is stored in a new array designated as b, which we subsequently output to the console.
Supported Browser
The browser supported by the Array concat method of JavaScript are:
- Firefox
- Safari
- Edge
- Chrome
- Opera
Conclusion
The concat method in JavaScript serves as an effective and straightforward approach for merging arrays and values. It operates safely, ensuring that the original arrays remain unaltered, making it ideal for scenarios where immutability is crucial. This method can amalgamate collections of items and permits the inclusion of additional values into the arrays being merged. As you begin to implement it, concat enhances your ability to manage arrays with greater efficiency.
Frequently Asked Questions (FAQs)
- What is the function of concat in JavaScript?
The concat function merges two or more arrays or values, resulting in a fresh array. It leaves the original array intact and instead produces a newly formed array.
- Does concat modify the original array?
No, the concat method does not mutate the original arrays. It maintains the integrity of the initial arrays and produces a new array that consists of the merged elements.
Example
let a = [1, 2];
let b = a.concat(3, 4);
console.log (a);
console.log (b);
Output:
The concat method can be utilized to combine both individual values and arrays. When you employ concat, you can append single elements such as numbers or strings directly to an array, in addition to merging multiple arrays together. For instance, if you have an existing array and you wish to include a solitary value, you can easily do so by passing that value as an argument to the concat function.
Here’s a simple example illustrating this:
let array1 = [1, 2, 3];
let singleValue = 4;
let newArray = array1.concat(singleValue); // Result: [1, 2, 3, 4]
Moreover, you can also concatenate additional arrays with the existing one:
let array2 = [5, 6];
let combinedArray = array1.concat(array2); // Result: [1, 2, 3, 5, 6]
In summary, the concat method is versatile enough to handle both individual values and arrays effortlessly.
The concat method can be utilized to append individual values as well as arrays.
Example
let arr = [1, 2];
let result = arr.concat(3, [4, 5]);
console.log(result);
Output:
Yes, it is indeed possible to merge more than two arrays using the concat method. The concat function is designed to concatenate multiple arrays, allowing you to combine them into a single array seamlessly. For example:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const array3 = [7, 8, 9];
const combinedArray = array1.concat(array2, array3);
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In this illustration, array1, array2, and array3 are all joined into one unified array called combinedArray. You can include as many arrays as you wish in the concat method, making it a versatile tool for array manipulation.
Indeed, you have the flexibility to pass numerous arrays or values as you wish.
Example
let a = [1];
let b = [2];
let c = [3];
let result = a.concat(b, c);
console.log(result);
Output:
[ 1, 2, 3, 4, 5, 6 ]
- Can I chain concat calls?
Indeed. As the concat method generates a new array, it is possible to link several concat calls in succession.
Example
let a = [1];
let result = a.concat([2]).concat ([3, 4]);
console.log(result);
Output:
[ 1, 2, 3, 4 ]
- Is concat only for arrays?
The concat function is primarily an array method; however, it is capable of taking both array and non-array inputs, including numbers, strings, Booleans, and more. The outcome of this operation is consistently a fresh array.