Tips on invoking a function from an array in JavaScript when a button is clicked

Being new to JavaScript, I encountered a challenge where I have an array of functions:

allFunctions = () => [
  function1(),
  function2(),
  function3(),
  function4(),
  function5(),
  function6(),
  function7(),
  function8(),
  function9()
]

My goal is to execute these functions and identify which one returns a 'true' value. Once identified, I want to reuse that specific function when a button is clicked.

When calling allFunctions(), the output is:

[false, false, false, true, false, false, false, false, false]

I am looking for assistance on how to trigger the function that returned true upon button click. Any guidance or help would be greatly appreciated. Thanks in advance.

Answer №1

To create an array of functions without executing them, you can use the following approach: Define multiple functions within an array and then access and execute them using Array.find() method to retrieve the first function that returns true or by utilizing Array.indexOf() method to find all functions that return true:

const fnFalse = () => false
const fnTrue = () => true

const allFunctions = [fnFalse, fnFalse, fnFalse, fnFalse, fnFalse, fnTrue, fnFalse, fnFalse, fnFalse]

const trueFn = allFunctions.find(fn => fn())

console.log(trueFn.name, trueFn())

You can apply a similar logic to the produced array named allFunctions by using Array.indexOf():

const fnFalse = () => false
const fnTrue = () => true

const fns = [fnFalse, fnFalse, fnFalse, fnFalse, fnFalse, fnTrue, fnFalse, fnFalse, fnFalse]

const allFunctions = () => [fnFalse(), fnFalse(), fnFalse(), fnFalse(), fnFalse(), fnTrue(), fnFalse(), fnFalse(), fnFalse()]

const trueFn = fns[allFunctions().indexOf(true)]

console.log(trueFn.name, trueFn())

Answer №2

If I understand correctly, here is a simple way to implement this using two buttons.

<button type="button" id="find">Find</button>
<button type="button" id="search">Search</button>

Now let's add the JavaScript code:

var functions = {
    find: function() { alert("finding..."); },
    search: function() { console.log("searching..."); }
};
document.getElementById ("find")
    .addEventListener ("click", handleClick);
document.getElementById ("search")
    .addEventListener ("click", handleClick);

function handleClick(event) {
    functions[event.target.id]();
}

You can further enhance this logic as per your requirements.

For an example, check out this JSFiddle.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Save to a JSON file

Hey there, I'm having some trouble with pushing a temporary value to a JSON file using the command "MyJSON.name.push". It keeps giving me an error saying "Undefined is not an object". I've tried different approaches and using JavaScript arrays wo ...

Refresh the page once the function has been executed

Recently, I came across a basic javascript code that I need some help with. I want to reload the page after certain elements have faded out and back in. The problem is, I'm not sure where exactly I should include the window.location.reload(); function ...

Trigger the execution of a Python script through a webpage with just the click of a button

I have a small web interface where I need to control a Python script that is constantly gathering data from a sensor in a while loop. Ideally, I would like the ability to start and stop this script with the click of a button. While stopping the script is s ...

Locate the Highest Number within a Multi-Dimensional Array and Store it in a Fresh Array

I'm currently tackling a coding challenge that involves working with nested arrays. The task is to find the largest number in each sub-array and then create a new array containing only the largest numbers from each one. Initially, my approach was to d ...

socket.io initialization and finalization events

Currently, I am integrating socket.io with express 3 for my application development. I am interested in implementing loader animations that will appear when a message is incoming and disappear once the message has been received. Similar to how jQuery&apos ...

Is it possible to log out a user in JavaScript by simply removing cookies?

Hey there, I currently have a node.js server running in the background which handles user login processes (I didn't create the backend code). app.use(function (req, res, next) { var nodeSSPI = require('node-sspi'); var nodeSSPIObj = n ...

A step-by-step guide on increasing native Time variables in JavaScript

How can I dynamically and repetitively add time (both hours and minutes) in JavaScript to effectively increment a date object? There are times when I need to add minutes, or hours, or a combination of both - and I want the resulting total time to be return ...

How can TypeScript leverage the power of JavaScript libraries?

As a newcomer to TypeScript, I apologize if this question seems simplistic. My goal is to incorporate JavaScript libraries into a .ts file while utilizing node.js for running my program via the console. In my previous experience with JavaScript, I utilize ...

Is there a problem with addEventListener returning false?

What does keeping the third parameter as false in the line below signify? var el = document.getElementById("outside"); el.addEventListener("click", modifyText, false); ...

Move the image inside the box without directly following the mouse cursor, but at a slightly faster pace

I am facing an issue with a Vue component that allows me to zoom in on an image and move it around the container. The problem is, when the image is zoomed in, it moves faster than the mouse due to using the scale transform. Additionally, I noticed that cl ...

What is the best way to align a series of divs vertically within columns?

Struggling to find the right words to ask this question has made it difficult for me to locate relevant search results. However, I believe a picture is worth a thousand words so...https://i.stack.imgur.com/LfPMO.png I am looking to create multiple columns ...

I am experiencing issues with my local MongoDB database not properly storing data when using Express and Mongoose

I am encountering an issue where my code is functioning correctly in the console but it is not saving data to the database. Every time I restart the server, the data gets reset. While I can read data from the database without any problem, the issue arise ...

creating an animated loop within an Angular template

How can we display a dynamic loop in Angular template using an array of object data? [ { "name": "name", "text": "text", "replies": [{ "name": "Reply1", "t ...

Every key must be a string or number; received a function instead

I encountered a peculiar situation while working with Cucumber: Scenario Outline: Protractor and Cucumber Test InValid Given I have already...... When I fill the <number> .... Examples: | number|... | 3 |... |4 |... Moreover, I ...

Identifying Shifts in Objects Using Angular 5

Is there a way to detect changes in an object connected to a large form? My goal is to display save/cancel buttons at the bottom of the page whenever a user makes changes to the input. One approach I considered was creating a copy of the object and using ...

Utilize the ng2-select component to incorporate multiple instances within a single webpage

Can someone help me figure out how to use two ng2-select components in my modal? I've checked out the documentation, but it doesn't provide any information on using more than one select. I'm not sure how to capture the selected values of ea ...

Leveraging ES6 import declarations within Firebase functions

I've been experimenting with using ES6 in Firebase functions by trying to import modules like "import App from './src/App.js'. However, after adding type:"module" to my package.json, I encountered a strange error with Firebase ...

Using Node.js, Express.js, and Redis.io for efficient order processing

Currently, I am working on a project that involves Node.js with express.js and redis.io as the database. I have implemented a get resource with query parameters to retrieve the IDs of libraries containing a specific book. However, I am struggling to unders ...

The response body in Express is returned as a ReadableStream instead of the typical JSON format

When using Express to create an API endpoint, I typically respond with res.json() to send a JSON object in the response that can be consumed by the client. In my API, I am implementing batched promises, resolving them, and sending back an object. However ...

Using tabs within a Dialog prevents the Dialog from adjusting its height automatically

Solved: Find the solution in the comments section below. I recently built a Tabs feature within a Dialog box, but ran into an issue where the height of the Dialog did not match up with the height of the tab. The problem arose when a form was placed insid ...