Saturday, July 18, 2020

add multiple array elements to array in single shot


Ref: MDN Documentation

Using apply to append an array to another

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


const array = ['a', 'b'];
const elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

No comments:

Post a Comment

function declaration, expression and call/invoke/execution

  The  function  declaration defines a function with the specified parameters. The  function   keyword can be used to define a function ins...