Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to chain array.push() in Javascript?

Tags:

javascript

I have 3 separate arrays and I'm looking to load them all into to a single array. Am I able to use .push() several arrays into one? Is something like this possible?

 var activeMembers=[];      // Active Users
 var noactiveMsg=[];        // Non-Active Users with a Pending Message
 var noactiveNomsg=[];      // Non-Active Users without a Pending Message
 var chatCenterMembers=[];          // Final Array of Chat Center Members


 chatCenterMembers.push(activeMembers).push(noactiveMsg).push(noactiveNomsg);

Is there a way to chain .push()?

like image 993
Adam Avatar asked Aug 19 '11 00:08

Adam


People also ask

Can you chain array methods JavaScript?

As most of the array methods return an array, the methods can be chained and used consecutively to make your code more concise.

Can I push an array into another array JavaScript?

To append one array to another, use the push() method on the first array, passing it the values of the second array. The push method is used to add one or more elements to the end of an array. The method changes the contents of the original array. Copied!

Can you push multiple values in array in JavaScript?

Use the Array. push() method to push multiple values to an array, e.g. arr. push('b', 'c', 'd'); . The push() method adds one or more values to the end of an array.

Can we push function in array?

push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.


2 Answers

You're looking for the (vanilla) JavaScript method Array.concat().

Returns a new array comprised of this array joined with other array(s) and/or value(s).

Example, following your code:

chatCenterMembers = chatCenterMembers
    .concat(activeMembers)
    .concat(noactiveMsg)
    .concat(noactiveNomsg);
like image 111
Matt Ball Avatar answered Oct 08 '22 11:10

Matt Ball


chatCenterMembers.push(activeMembers,noactiveMsg,noactiveNomsg)
like image 39
mowwwalker Avatar answered Oct 08 '22 10:10

mowwwalker