skip to Main Content

There is an array of functions that execute different code. It is necessary to make one function out of these functions, when called, all functions from the array would be executed at once.

const a = ()=>{console.log("1")};
const b = ()=>{console.log("2")};
const arr = [a,b];
const fn = () =>{
 arr[0]();
 arr[1]();
}

I need to make such a result in code, rather than manually calling functions.

I tried to do this by simply iterating through the array using a for loop, but the question is, is there any way to do this without increasing the index? Should I use it as a recursive function or something else?

Solving the problem using a loop:

const fn = () =>{
 for(let i = 0; i < arr.length; i++){
  arr[i]();
 }
}

Is there some solution that doesn’t use a loop? Maybe nest a function within a function somehow?

3

Answers


  1. You can use the forEach() method like this:

    const a =()=>{console.log("1")};
    const b =()=>{console.log("2")};
    const c =()=>{console.log("2")};
    const d =()=>{console.log("2")};
    const e =()=>{console.log("2")};
    const f =()=>{console.log("2")};
    const arr = [a,b,c,d,e,f];
    
    arr.forEach(x => x());
    
    /* Or wrap it in another function if you want to run it whenever needed
    
    const func = () => arr.forEach(x => x());
    func();
    
    */
    Login or Signup to reply.
  2. Here’s one I use, to run them asynchronously in a way. This is to avoid hanging the event loop, there is a small timeout between the calls.

    function run_all(queue) {
      if (!queue.length) {
        return;
      }
    
      function do_one(foo, foo_then) {
        foo();
        setTimeout(foo_then)
      }
    
      var first = queue.shift();
      do_one(first, function() {
        run_all(queue)
      })
    }
    
    var arr = []
    arr.push(() => console.log("hello"))
    arr.push(() => console.log("hello 2"))
    run_all(arr)
    Login or Signup to reply.
  3. Another way to loop through arrays is to use the array’s built-in forEach() method.Each item of the array is passed to the function one by one.

    myArray.forEach( function(item) {
    doSomething(item);
    });
    
    const fruit = ['Apples', 'Oranges', 'Bananas', 'Pears'];
    fruit.forEach(function(item) {
    console.log(item);
    });
    

    Also reference: Why is my forEach loop not editing my array?
    {The forEach() method does not directly manipulate array indices.}

    I hope this helps. Happy coding!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search