Merge multiple arrays to one array in jquery
Asked Answered
R

3

5

I am trying to merge my multiple arrays to one array using jquery. I know that we can merge two arrays to one using jquery merge function. And we can loop through those arrays and join them to one too. But I just wanted to know whether there is any other way to achieve this without using any loop. I am handling large number of datas. So I can expect any number of arrays too. I am worrying if we use a loop, it may affect the performance. Please give me some suggestions. Thanks in advance.

Kindest Regards Sibeesh Venu

Rahr answered 18/8, 2015 at 7:20 Comment(0)
S
14

use .concat

and to apply it for multiple array like below

var multipleArrays = [[1,2], [3,4], [5,6]];

var flatArray = [].concat.apply([], multipleArrays); 
// [1, 2, 3, 4, 5, 6]

// Using the Spread syntax
var flatArray2 = Array.prototype.concat(...multipleArrays);
// [1, 2, 3, 4, 5, 6]
Stingo answered 18/8, 2015 at 7:25 Comment(3)
no sense use .concat.apply -- concat return new array itselfSapp
if OP has dynamic number of arrays, use cocnat.apply would be easierStingo
I will try this method and let you know. Thank youRahr
Z
6

array1.concat(array2) in plain javascript

Zygospore answered 18/8, 2015 at 7:22 Comment(2)
As I said in the question, I need to merge so many arrays. Not just two. I have tried this method. Thank youRahr
just chain the function then: array1.concat(array2).concat(array3)Zygospore
S
2

You can just push all values from one to another

var a = [1,2,3]
var b = [2,3,4,5]
a.push.apply(a, b)
console.log(a);// [1, 2, 3, 2, 3, 4, 5]
Sapp answered 18/8, 2015 at 7:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.