Javascript Array of Functions

JavascriptArraysFunction

Javascript Problem Overview


var array_of_functions = [
	first_function('a string'),
	second_function('a string'),
	third_function('a string'),
	forth_function('a string')
]

array_of_functions[0];

That does not work as intended because each function in the array is executed when the array is created.

What is the proper way of executing any function in the array by doing:

array_of_functions[0];  // or, array_of_functions[1] etc.

Thanks!

Javascript Solutions


Solution 1 - Javascript

var array_of_functions = [    first_function,    second_function,    third_function,    forth_function]

and then when you want to execute a given function in the array:

array_of_functions[0]('a string');

Solution 2 - Javascript

I think this is what the original poster meant to accomplish:

var array_of_functions = [
    function() { first_function('a string') },
    function() { second_function('a string') },
    function() { third_function('a string') },
    function() { fourth_function('a string') }
]

for (i = 0; i < array_of_functions.length; i++) {
    array_of_functions[i]();
}

Hopefully this will help others (like me 20 minutes ago :-) looking for any hint about how to call JS functions in an array.

Solution 3 - Javascript

Without more detail of what you are trying to accomplish, we are kinda guessing. But you might be able to get away with using object notation to do something like this...

var myFuncs = {
  firstFunc: function(string) {
    // do something
  },

  secondFunc: function(string) {
    // do something
  },

  thirdFunc: function(string) {
    // do something
  }
}

and to call one of them...

myFuncs.firstFunc('a string')

Solution 4 - Javascript

I would complement this thread by posting an easier way to execute various functions within an Array using the shift() Javascript method originally described here

  var a = function(){ console.log("this is function: a") }
  var b = function(){ console.log("this is function: b") }
  var c = function(){ console.log("this is function: c") }

  var foo = [a,b,c];

  while (foo.length){
     foo.shift().call();
  }

Solution 5 - Javascript

Or just:

var myFuncs = {
  firstFun: function(string) {
    // do something
  },

  secondFunc: function(string) {
    // do something
  },

  thirdFunc: function(string) {
    // do something
  }
}

Solution 6 - Javascript

It's basically the same as Darin Dimitrov's but it shows how you could use it do dynamically create and store functions and arguments. I hope it's useful for you :)

var argsContainer = ['hello', 'you', 'there'];
var functionsContainer = [];

for (var i = 0; i < argsContainer.length; i++) {
var currentArg = argsContainer[i]; 

  functionsContainer.push(function(currentArg){
    console.log(currentArg);
  });
};

for (var i = 0; i < functionsContainer.length; i++) {
  functionsContainer[i](argsContainer[i]);
}

Solution 7 - Javascript

up above we saw some with iteration. Let's do the same thing using forEach:

var funcs = [function () {
        console.log(1)
  },
  function () {
        console.log(2)
  }
];

funcs.forEach(function (func) {
  func(); // outputs  1, then 2
});
//for (i = 0; i < funcs.length; i++) funcs[i]();

Solution 8 - Javascript

Ah man there are so many weird answers...

const execute = (fn) => fn()
const arrayOfFunctions = [fn1, fn2, fn3]

const results = arrayOfFunctions.map(execute)

or if you want to sequentially feed each functions result to the next:
compose(fn3, fn2, fn1)

compose is not supported by default, but there are libraries like ramda, lodash, or even redux which provide this tool

Solution 9 - Javascript

This is correct

var array_of_functions = {
    	  	"all": function(flag) { 
    		  	console.log(1+flag); 
    		  },
      	        "cic": function(flag) { 
    			console.log(13+flag); 
    		  } 					
    	};

array_of_functions.all(27);
array_of_functions.cic(7);

Solution 10 - Javascript

If you're doing something like trying to dynamically pass callbacks you could pass a single object as an argument. This gives you much greater control over which functions you want to you execute with any parameter.

function func_one(arg) {
    console.log(arg)
};

function func_two(arg) {
    console.log(arg+' make this different')
};

var obj = {
    callbacks: [func_one, func_two],
    params: ["something", "something else"];
};

function doSomething(obj) {
    var n = obj.counter
    for (n; n < (obj.callbacks.length - obj.len); n++) {
        obj.callbacks[n](obj.params[n]);
    }
};

obj.counter = 0;
obj.len = 0;
doSomething(obj); 

//something
//something else make this different

obj.counter = 1;
obj.len = 0;
doSomething(obj);

//something else make this different

Solution 11 - Javascript

Execution of many functions through an ES6 callback 珞

const f = (funs) => {
  funs().forEach((fun) => fun)
}

f(() => [
  console.log(1),
  console.log(2),
  console.log(3)
])

Solution 12 - Javascript

Using ES6 syntax, if you need a "pipeline" like process where you pass the same object through a series of functions (in my case, a HTML abstract syntax tree), you can use for...of to call each pipe function in a given array:

const setMainElement = require("./set-main-element.js")
const cacheImages = require("./cache-images.js")
const removeElements = require("./remove-elements.js")

let htmlAst = {}

const pipeline = [
    setMainElement,
    cacheImages,
    removeElements,
    (htmlAst) => {
        // Using a dynamic closure.
    },
]

for (const pipe of pipeline) {
    pipe(htmlAst)
}

Solution 13 - Javascript

Maybe it can helps to someone.

<!DOCTYPE html>
<html>
   <head lang="en">
      <meta charset="UTF-8">
      <title></title>
      <script type="text/javascript">
         window.manager = {
             curHandler: 0,
             handlers  : []
         };
         
         manager.run = function (n) {
             this.handlers[this.curHandler](n);
         };
         
         manager.changeHandler = function (n) {
             if (n >= this.handlers.length || n < 0) {
                 throw new Error('n must be from 0 to ' + (this.handlers.length - 1), n);
             }
             this.curHandler = n;
         };
         
         var a = function (n) {
             console.log("Handler a. Argument value is " + n);
         };
         
         var b = function (n) {
             console.log("Handler b. Argument value is " + n);
         };
         
         var c = function foo(n) {
             for (var i=0; i<n; i++) {
                 console.log(i);
             }
         };
         
         manager.handlers.push(a);
         manager.handlers.push(b);
         manager.handlers.push(c);
      </script>
   </head>
   <body>
      <input type="button" onclick="window.manager.run(2)" value="Run handler with parameter 2">
      <input type="button" onclick="window.manager.run(4)" value="Run handler with parameter 4">
      <p>
      <div>
         <select name="featured" size="1" id="item1">
            <option value="0">First handler</option>
            <option value="1">Second handler</option>
            <option value="2">Third handler</option>
         </select>
         <input type="button" onclick="manager.changeHandler(document.getElementById('item1').value);" value="Change handler">
      </div>
      </p>
   </body>
</html>

Solution 14 - Javascript

A short way to run 'em all:

[first_function, ..., nth_function].forEach (function(f) {
    f('a string');
}); 

Solution 15 - Javascript

the probleme of these array of function are not in the "array form" but in the way these functions are called... then... try this.. with a simple eval()...

array_of_function = ["fx1()","fx2()","fx3()",.."fxN()"]
var zzz=[];
for (var i=0; i<array_of_function.length; i++)
     { var zzz += eval( array_of_function[i] ); }

it work's here, where nothing upper was doing the job at home... hopes it will help

Solution 16 - Javascript

Using Function.prototype.bind()

var array_of_functions = [
        first_function.bind(null,'a string'),
        second_function.bind(null,'a string'),
        third_function.bind(null,'a string'),
        forth_function.bind(null,'a string')
    ]

Solution 17 - Javascript

I have many problems trying to solve this one... tried the obvious, but did not work. It just append an empty function somehow.

array_of_functions.push(function() { first_function('a string') });

I solved it by using an array of strings, and later with eval:

array_of_functions.push("first_function('a string')");

for (var Func of array_of_functions) {
   eval(Func);
   }

Solution 18 - Javascript

maybe something like this would do the trick:

[f1,f2,f3].map((f) => f('a string'))

Solution 19 - Javascript

This answered helped me but I got stuck trying to call each function in my array a few times. So for rookies, here is how to make an array of functions and call one or all of them, a couple different ways.

First we make the array.

let functionsArray = [functionOne, functionTwo, functionThree];

We can call a specific function in the array by using its index in the array (remember 0 is the first function in the array).

functionsArray[0]();

We have to put the parenthesis after because otherwise we are just referencing the function, not calling it.

If you wanted to call all the functions we could use a couple different ways.

For loop

for (let index = 0; index < functionsArray.length; index++) {
  functionsArray[index]();
}

Don't forget the parenthesis to actually call the function.

ForEach ForEach is nice because we don't have to worry about the index, we just get handed each element in the array which we can use. We use it like this (non arrow function example below):

functionsArray.forEach(element => {
    element();
});

In a ForEach you can rename element in the above to be whatever you want. Renaming it, and not using arrow functions could look like this:

functionsArray.forEach(
    function(funFunctionPassedIn) {
        funFunctionPassedIn();
    }
);

What about Map? We shouldn't use Map in this case, since map builds a new array, and using map when we aren't using the returned array is an anti-pattern (bad practice).

We shouldn't be using map if we are not using the array it returns, and/or we are not returning a value from the callback. Source

Solution 20 - Javascript

you got some top answers above. This is just another version of that.

var dictFun = {
     FunOne: function(string) {
     console.log("first function");
  },

   FuncTwo: function(string) {
   console.log("second function");
 },

  FuncThree: function(string) {
   console.log("third function");
}

}

Solution 21 - Javascript

/* PlanetGreeter */

class PlanetGreeter {
    hello   : { () : void; } [] = [];
    planet_1 : string = "World";
    planet_2 : string = "Mars";
    planet_3 : string = "Venus";
    planet_4 : string = "Uranus";
    planet_5 : string = "Pluto";
    constructor() {
        this.hello.push( () => { this.greet(this.planet_1); } );
        this.hello.push( () => { this.greet(this.planet_2); } );
        this.hello.push( () => { this.greet(this.planet_3); } );
        this.hello.push( () => { this.greet(this.planet_4); } );
        this.hello.push( () => { this.greet(this.planet_5); } );
    } 
    greet(a: string) : void { alert("Hello " + a); }
    greetRandomPlanet() : void { 
        this.hello [ Math.floor( 5 * Math.random() ) ] (); 
    } 
} 
new PlanetGreeter().greetRandomPlanet();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNickView Question on Stackoverflow
Solution 1 - JavascriptDarin DimitrovView Answer on Stackoverflow
Solution 2 - JavascriptpjcabreraView Answer on Stackoverflow
Solution 3 - JavascriptJeffView Answer on Stackoverflow
Solution 4 - JavascriptGusView Answer on Stackoverflow
Solution 5 - JavascriptRobinView Answer on Stackoverflow
Solution 6 - JavascriptMensur GriševićView Answer on Stackoverflow
Solution 7 - JavascriptmlhazanView Answer on Stackoverflow
Solution 8 - JavascriptDaniel TokView Answer on Stackoverflow
Solution 9 - JavascriptLeonardo CiaccioView Answer on Stackoverflow
Solution 10 - JavascriptDaniel LizikView Answer on Stackoverflow
Solution 11 - JavascriptThomas GotwigView Answer on Stackoverflow
Solution 12 - JavascriptSteve BaumanView Answer on Stackoverflow
Solution 13 - JavascriptHopkroftView Answer on Stackoverflow
Solution 14 - JavascriptDanyal AytekinView Answer on Stackoverflow
Solution 15 - JavascriptQuetzalView Answer on Stackoverflow
Solution 16 - JavascriptYakuZaView Answer on Stackoverflow
Solution 17 - JavascriptNezumiView Answer on Stackoverflow
Solution 18 - JavascriptRichard O'BrienView Answer on Stackoverflow
Solution 19 - JavascriptJoshua DanceView Answer on Stackoverflow
Solution 20 - Javascriptpallimula stackoverflowView Answer on Stackoverflow
Solution 21 - Javascriptuser37057View Answer on Stackoverflow