AppDividend
Latest Code Tutorials

Javascript Array Concat Example | JS Array concat() Method

0

Javascript Array concat() is an inbuilt method that is used to merge the two or more arrays. The concat() function does not modify the existing array but instead returns the new array. The concat() method does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains copies of the same elements combined from the original arrays.

Javascript Array Concat Example

Javascript array concat() method does not change the existing arrays but returns a new array containing the values of the joined arrays. It is the sign of immutability of objects because you can not merely change anything inside an array.

It counts as a pure function, and pure function always returns a new copy of the existing array of objects. If you have used Redux previously, then you have known that we used this concat function to return a new state of the class and not modify that state of the class.

Syntax

array1.concat(array2, array3, ..., arrayX)

#Concatenating two arrays in Javascript

Okay, first, we will test all of our examples in node.js because it is the simplest way, and we did not need to write any HTML file to see the output in the console. So it is an easy setup for this example.

Just create one project folder and inside that create one file called concatarray.js and add the following code inside it.

// concatarray.js

let realmadrid = ['Gareth Bale', 'Karim Benzema', 'Sergio Ramos'];
let barcelona = ['Messi', 'Luis suarez', 'Gerard Pique'];

let players = realmadrid.concat(barcelona);

console.log(players);

Go to the terminal or cmd and type the following command.

node concatarray

So, here you can see the output like this.

Javascript Array Concat Example

So, it has returned a new array, which is the addition of both of the arrays, and now you can check the individual both the arrays and see that none of them are changed. So, it is the pure function that returns a new array without modifying the existing one.

#How to concat three arrays in Javascript

We can add more than two arrays. Let us add three arrays.

// concatarray.js

let realmadrid = ['Gareth Bale', 'Karim Benzema', 'Sergio Ramos'];
let barcelona = ['Messi', 'Luis suarez', 'Gerard Pique'];
let chelsea = ['Ngolo Kante', 'Pedro', 'Olivier Geraud']

let players = realmadrid.concat(barcelona, chelsea);

console.log(players);

So the concat function takes minimum one argument and maximum as you like.

#How to concat values to an array

Now, let us concat alphanumeric arrays in the following example.

// concatarray.js

let realmadrid = ['Gareth Bale', 'Karim Benzema', 'Sergio Ramos'];
let alphaNumeric = realmadrid.concat(1, [2, 3], [4,5,6,7,8]);

console.log(alphaNumeric);

See in the above example; the first array is full of strings, and the second array is integer and array of arrays.

See the output.

Array Concat In Javascript

So, that means it adds all the items inside one array and then returns it. If the items are the array of arrays, then still, it will return only one array containing all the items. So the result will not be an array of arrays. It is the single values, whether it is integer or string.

#Concatenating nested arrays in Javascript

As I have said earlier, if we concat array of arrays, then it will return a single array in which not a single element will be an array.

// concatarray.js

let numeric = [10, 11, 12, 13];
let arrayNumeric = numeric.concat(1, [2, 3], [4,5,6,7,8]);

console.log(arrayNumeric);

Output

Array Concat() example

#Versions of Javascript Array concat() method

Let’s see the two versions of the js array concat() method.

# app.js

gym = ['??‍♂️', '??‍♂️', '??‍♂️']
sports = ['⛹️‍♀️', '??‍♂️', '?']

// Version A:
const combinedExerciseA = [].concat(gym, sports);
console.log(combinedExerciseA)

// Version B:
const combinedExerciseB = gym.concat(sports);
console.log(combinedExerciseB)

Output

node app
[ '??‍♂️', '??‍♂️', '??‍♂️', '⛹️‍♀️', '??‍♂️', '?' ]
[ '??‍♂️', '??‍♂️', '??‍♂️', '⛹️‍♀️', '??‍♂️', '?' ]

You can see that we got the same output.

Now the question is, what should we use and why?

I prefer Version A because I think the intention of that approach is lot more clear. Just by looking at it, I know that I’m creating a new array, and I’m not manipulating an existing array.

Whereas if I look at Version B, it appears like I’m adding the gym array to the sports array, and it doesn’t seem obvious to me that the gym array isn’t being changed. But, maybe that’s just me. I would be curious to know what you think?

Since I don’t have any substantial reason besides aesthetics, I think you and your team should stick with whatever you choose ?.

#Difference between Spread Operator vs. Array Concat

I prefer using ES6 spread operator because I find it more concise and more comfortable to write. BUT, there are still benefits of using the concat() method.

The spread operator is fantastic when you know beforehand that you’re dealing with arrays. But what happens when the source is something else, like a string. And you want to add that string to the array. Let’s walk through an example.

Array concat using the Spread operator

See the following code.

// app.js

gym = ['??‍♂️', '??‍♂️', '??‍♂️']
sports = ['⛹️‍♀️', '??‍♂️', '?']

const combinedUsingSpread = [...gym, ...sports]
console.log(combinedUsingSpread)

Output

 node app
[ '??‍♂️', '??‍♂️', '??‍♂️', '⛹️‍♀️', '??‍♂️', '?' ]

In this case, the spread operator works as a concat() function because all the elements are the type of array.

Let’s take a scenario in which one data type is an array that contains characters, and one is a string and then uses the spread operator to combine two values.

// app.js

gym = ['??‍♂️', '??‍♂️', '??‍♂️']
sports = 'Chess'

const combinedUsingSpread = [...gym, ...sports]
console.log(combinedUsingSpread)

Output

 node app
[
  '??‍♂️', '??‍♂️',
  '??‍♂️', 'C',
  'h',       'e',
  's',       's'
]

From the output, you can see that the string spreads into its characters.

We have not intended this output.

Let’s use the array concat() method and see the output.

// app.js

gym = ['??‍♂️', '??‍♂️', '??‍♂️']
sports = 'Chess'

const combinedUsingConcat = gym.concat(sports)
console.log(combinedUsingConcat)

Output

node app
[ '??‍♂️', '??‍♂️', '??‍♂️', 'Chess' ]

Excellent! We get the result we want.

So here’s the quick rule. If you know, you’re dealing with arrays, use spread operator. But if you might be dealing with the possibility with a non-array, then use the concat() method to merge an array ?.

Anyways I just want to the point that out, so you can use the most appropriate method depending on the problem you’re trying to solve ?.

Conclusion

Javascript concat() function creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array). It does not recurse into nested array arguments.

Finally, Javascript Array Concat Example is over.

See also

Javascript array filter()

Javascript array map()

Javascript array forEach()

Javascript array reduce()

Javascript array push()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.