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

What methods can be utilized to create sound effects in presentations using CSS?

Let us begin by acknowledging that: HTML is primarily for structure CSS mainly deals with presentation JS focuses on behavior Note: The discussion of whether presentation that responds to user interaction is essentially another term for behavior is open ...

ng filtering with a controller-defined scope

I am currently working on a webpage with AngularJS and I am looking to implement some filters on the site. Here is the HTML code I have: <div ng-repeat="data in datas | filter:{area:course} | filter:{subject:subFilter} | filter:{city:cityFilter}"> ...

How to Use Vue.js to Find the Nearest Div Element with a Specific

Below is the HTML code I am working with: <div id="app"> <div class="image"> <div class="overlay"> <p>Some overlay text</p> </div> <img src="https://placeimg.com/640/480/any" class="img-fluid"> ...

Tips for guiding users to a different page based on whether a linkid is associated with a specific Cat

I created this script, but I am facing an issue with the redirect. Can someone please assist me as soon as possible? <?php include('config.php'); $number = intval($_POST['catid']); $query = mysql_query("SELECT * FROM sound ...

Steps for calling a function in index.js using Node.js

I am just starting to learn about NodeJS and I have a question that might seem basic to some, but I would really appreciate some assistance here. Here is the content of my index.js file:- 'use-strict'; const { myauth } = require('./src/au ...

Loading jQuery on Ajax can be a challenge

I am currently faced with the challenge of working on code that I did not write myself or fully comprehend. The page utilizes AJAX to dynamically load content, and my goal is to manipulate this content. However, when I try to apply jQuery to the dynamic el ...

Customizing the Switch component individually for each item fetched from an API in React Native

I'm struggling with setting the switch button individually for each item in my API. Despite trying multiple solutions, none of them seem to work for me. const results = [ { Id: "IySO9wUrt8", Name: & ...

Set up a WhatsApp web bot on the Heroku platform

I am currently in the process of developing a WhatsApp bot using the node library whatsapp-web.js. Once I finish writing the script, it appears something like this (I have provided an overview of the original script) - index.js const {Client, LocalAuth, M ...

Executing JavaScript code from an external link

Currently, I am in the process of developing a horizontal parallax website. The functionality is working seamlessly; when I click on the menu, the slides smoothly transition horizontally and display the corresponding content. However, I have encountered a ...

How to position footer at the bottom of Material UI cards - see example below

After getting inspiration from the material-ui example of cards, I wanted to create a grid layout with multiple cards. My goal was to make all the cards have equal height (which I achieved using height:100%) and position the footer at the bottom of each ca ...

Utilizing JFlex for efficient brace matching

Currently, I am in the process of developing an IntelliJ plugin. One of the key features that I am working on is a brace matcher. After completing the JetBrains plugin tutorial, I was able to get the brace matcher functioning using this regular expression ...

What is the best way to access the iframe element?

This is main.html <body> <iframe id="frame" src="frame.html"></iframe> <script type="text/javascript"> document.getElementById('frame').contentWindow.document.getElementById('test').innerHtml = &apos ...

What is the most efficient way to transfer a large search results array between NodeJS and AngularJS?

My application is built with NodeJS for the back-end and AngularJS for the front-end. I've run into an issue where sending a search query from Angular's $http to the back-end results in a bottleneck when there is a slow internet connection. Angul ...

The browser is not displaying the results from Mongodb, yet they are appearing in the console

I am currently using the following code for my router: let mongoose = require('mongoose'); // connecting with our model let ByProduct = require('../models/Byproduct') router.get('/',(req,res,next)=>{ ByProduct.find().th ...

Application with menu design, similar to the layout of google.com on mobile devices

Have you seen the Android smartphone with Chrome from GOOGLE.COM? Did you notice the pop-up MENU that looks similar to an application? This menu has a "SPRING" effect, and I'm curious how Google achieved this result. I tried using the property "-web ...

Ensuring continuous execution of JS EventListener

The other day, I received a solution from someone on this platform for a script that changes the color of a div when scrolling. Here is the code I implemented: const x = document.getElementById("menuID"); window.addEventListener("scroll", () => { ...

Is it possible for me to pass a value through props that is not currently stored in the state?

Within the realm of Reactjs, imagine a scenario where there exists a <Parent> component containing state and a variable named foo, which is either 'global' or local to Parent. The question arises: Can we pass foo as props using <Child v ...

Is there a way to use JQuery to make one button trigger distinct actions in two different divs?

For instance: Press a button - one div flies off the screen while another div flies in. Press the button again - Same div flies out, other div returns. I'm completely new to Javascript/JQuery so any assistance would be highly appreciated! Thank you ...

The functionality of sending form data via Express.js router is restricted

In my current project, I am developing a basic CRUD functionality in express. My goal is to utilize the express.Router() to transmit form data via the HTTP POST method. The form structure on the browser appears as follows: form.png The process was flawle ...

Experiencing challenges with ng-repeat and the concept of 'distinct'

I'm facing a perplexing issue. When utilizing ng-repeat to iterate through my data and create checkboxes, I encounter unexpected behavior. The result is multiple duplicate items being displayed instead of unique ones. Here's an example: <lab ...