Click here to Skip to main content
15,867,453 members
Articles / All Topics

Merge Multiple Arrays To One

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
21 Aug 2015CPOL1 min read 13K   5  
How to merge multiple arrays to one

In this post, we will discuss how we can merge multiple arrays to one array using JQuery. There are so many ways to achieve this. Like we can loop through each array and push it to other array one by one or we can join those arrays one by one. Or we can use JQuery function merge(). But the requirement was a bit different. Since I was using large data, I was not able to use any loop or any long processes. We will discuss an easy way here in this tip. I hope you will like this.

Background

Recently, I got a requirement of merging large collections of client side arrays to one array. The problem was the arrays were dynamic, hence I was not sure about the count of those arrays, it may be different in different times. So what to do? A loop, merge, push, join in jquery was not a perfect solution for me since the data was large. So I found the solution in another way.

Using the Code

Consider we have some arrays as follows:

[21,2], [35,4], [25,6],[11,6],[44,67]

Now, we need to change these arrays to a variable.

JavaScript
var myArrays = [[21,2], [35,4], [25,6],[11,6],[44,67]];

Now, here comes the real part.

JavaScript
var myArray = [].concat.apply([], myArrays); 

We are using jquery concat and jquery apply() function.

Now we will write this array to console.

JavaScript
console.log(myArray);

See the console, you can get the values as follows:

Merge Multiple Arrays To One

Merge Multiple Arrays To One

You can see the demo at jsfiddle here: Merge Multiple Arrays To One

Conclusion

I hope someone found it useful. Please share me your valuable suggestions and feedback. Thanks in advance.

This article was originally posted at http://sibeeshpassion.com/merge-multiple-arrays-to-one

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Germany Germany
I am Sibeesh Venu, an engineer by profession and writer by passion. I’m neither an expert nor a guru. I have been awarded Microsoft MVP 3 times, C# Corner MVP 5 times, DZone MVB. I always love to learn new technologies, and I strongly believe that the one who stops learning is old.

My Blog: Sibeesh Passion
My Website: Sibeesh Venu

Comments and Discussions

 
-- There are no messages in this forum --