Site icon Sibeesh Passion

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 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.

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 other way.

Using the code

Consider we have some arrays as follows.

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

Now we need to change these arrays to a variable.

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

Now here comes the real part.

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

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

Now we will write this array to console.

[js]
console.log(myArray);
[/js]

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

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.

Kindest Regards
Sibeesh Venu

Exit mobile version