Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: push an entire list?

Tags:

javascript

Is there a built in way to append one list into another like so:

var a = [1,2,3];
a.append([4,5]);
// now a is [1,2,3,4,5];

concat() does something similar but returns the result. I want something that modifies the existing list like push()

like image 907
shoosh Avatar asked Jan 30 '11 12:01

shoosh


People also ask

Can you push an array into an array JavaScript?

Adding Array into the Array using push() To add an array into an array in JavaScript, use the array. push() method. The push() function allows us to push an array into an array. We can add an array into an array, just like adding an element into the Array.

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 you push to const array?

Even though the numbers array is a const you're able to update or change the variable. For example, you can add another number to the numbers array by using the push method. Methods are actions you perform on the array or object. const numbers = [1,2,3]; numbers.


2 Answers

push will work, but you also need to use apply.

var a = [1,2,3];
a.push.apply(a, [4,5])
like image 65
outis Avatar answered Oct 16 '22 15:10

outis


var list = [1, 2];

People already showed you how to do this with:

  1. push: list.push.apply(list, [3, 4]);
  2. concat: list = list.concat([4, 5]);

But I want to tell about ES6 spread operator: list.push(...[3, 4]);.

Keep in mind that currently not many browsers support it (you can use transpilers).

like image 24
Salvador Dali Avatar answered Oct 16 '22 14:10

Salvador Dali