0

Let's say I'm trying to push multiple calls like:

var fields = [1,2];
fields.push(test("#test1", 1));
fields.push(test("#test2", 2));
fields.push(test("#test3", 3));
fields.push(newTest("#test5", 3, 'something'));

function test(a, b){
   // something here
}

function newTest(a, b, c){
   // something here
}

Is there an efficient way to do this all in one call? Like:

fields.push(test({"#test1": 1, "#test2": 2, "#test3": 3}), newTest(3, 4, "something"));

or

fields.push(test(["#test1": 1, "#test2": 2, "#test3": 3]), newTest(3, 4, "something"));
Keith
  • 4,059
  • 2
  • 32
  • 56
  • 1
    Possible duplicate of [push multiple elements to array](https://stackoverflow.com/questions/14723848/push-multiple-elements-to-array) – Phiter Mar 06 '18 at 14:09

3 Answers3

1

What you're looking for is Array.prototype.concat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

fields = fields.concat(
    test("#test1", 1),
    test("#test2", 2),
    test("#test3", 3),
    newTest("#test5", 3, 'something')
);

If the value is an array, the values of that array are pushed instead of the whole array. Other values are pushed directly.

Kulvar
  • 1,139
  • 9
  • 22
1

There are several ways that you could add multiple values into an array with one command. You could create your own function as you mention in the question like shown below or use CONCAT like the other answer mentions. Here are two working examples that you can run to see how that works:

//Original Array
var fields = [1,2];

//Show original values
console.log(fields);

//Function call with multiple values
test([3,4,5,6,7]);

//Function to add each value sent to function in array
function test(valueArray){
   for (var i = 0; i < valueArray.length; i++)
   {
      var singleValue = valueArray[i];
      fields.push(singleValue);
   }
}

//Show the result
console.log(fields);

//OR CONCAT TO DO THE SAME THING EASILY
fields = [1,2];;
fields = fields.concat(3,4,5,6,7);
console.log(fields);
MUlferts
  • 1,310
  • 2
  • 16
  • 30
0

You can do something like this if you want to add all at once:

var fields = [];

function test(a, b){
   return a+' '+b;
}

function newTest(a, b, c){
   return a+' '+b+' '+c;
}

fields.push(test("#test1",1),test("#test2",2),test("#test3",3),newTest("#newTest1",1,1));
console.log(fields);
buki
  • 18
  • 2