Merge Multiple Arrays Into One in jQuery

This article explains how to merge multiple arrays into one array using jQuery. There are many ways to do this. Like we can loop through each array and push it to another array one by one or we can join those arrays one by one. Or we can use the jQuery function merge(). But the requirement was a bit different. Since I was using a large amount of data, I was not able to use any loop or any long processes. We will explain in an easy way here in this article. I hope you will like this.

Please see this article in my blog.

Background

Recently I got the requirement for merging large collections of client-side arrays into one array. The problem was the arrays were dynamic, hence I was not sure of the count of the arrays, it may be different at 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

Assume we have some arrays as follows.

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

Now we need to change these arrays into a variable.

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

Now here comes the real part.

  1. var myArray = [].concat.apply([], myArrays);   
We are using the jQuery concat and jQuery apply() functions.

Now we will write this array to the console.
  1. 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 finds this useful. Please share with me your valuable suggestions and feedback. Thanks in advance.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now