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"));
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.