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()
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.
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.
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.
push
will work, but you also need to use apply
.
var a = [1,2,3];
a.push.apply(a, [4,5])
var list = [1, 2];
People already showed you how to do this with:
list.push.apply(list, [3, 4]);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With