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 requirement was 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 article. I hope you will like this.
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 other 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.
var myArrays = [[21,2], [35,4], [25,6],[11,6],[44,67]];
Now here comes the real part.
var myArray = .concat.apply(, myArrays);
We are using jquery concat and jquery apply() function.
Now we will write this array to console.
See the console, you can get the values as follows.
You can see the demo at jsfiddle here: Merge Multiple Arrays To One
I hope someone found it useful. Please share me your valuable suggestions and feedback. Thanks in advance.