Please Login to Continue

Free Software Development Articles.Email List

Advertise Here

[JavaScript Array push.apply()] Load content to Array without creating array inside array

[NB] I did not write this content: This content is not mine, it is copied straight from the website referenced in the link:

Using apply to append an array to another

We can use push to append an element to an array. And, because push accepts a variable number of arguments, we can also push multiple elements at once. But, if we pass an array to push, it will actually add that array as a single element, instead of adding the elements individually, so we end up with an array inside an array. What if that is not what we want? concat does have the behaviour we want in this case, but it does not actually append to the existing array but creates and returns a new array. But we wanted to append to our existing array... So what now? Write a loop? Surely not?

apply to the rescue!var array = ['a', 'b']; var elements = [0, 1, 2]; array.push.apply(array, elements); console.info(array); // ["a", "b", 0, 1, 2]


Technology published
Buy Me Coffee

Was this page helpful?

Yes Yes! this solution to the problem was helpful. No No! this solution to the problem was not helpful..
Buy Me Coffee

How to Draw Realistic Photos (E-Book)

How to Draw Realistic Photos (E-Book)

$1

Why Software Development Need Ethics to Succeed (E-Book)

Why Software Development Need Ethics to Succeed (E-Book)

$1

How to Make a Social Media Website in Easy Steps

How to Make a Social Media Website in Easy Steps

$1




© 2020 - ErnesTech - Privacy