Determine in JavaScript whether an array includes a function in its elements

Currently, I am adding anonymous functions to an array in the following manner:

myArray.push(function(){ /* some unique code here */});
myArray.push(function(){ /* even more unique code here */});

Afterwards, I execute all the functions by doing

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

The query at hand is: How can I determine if a function already exists in myArray? I attempted using toSource() for comparison, but unfortunately, it did not yield the desired result... Any suggestions?

Appreciate any insight provided ahead of time.

Answer №1

Compare the functions by converting them to strings:

func1.toString() === func2.toString()

Even anonymous functions can be compared this way, as long as you are looking for exact matches in code.

Answer №2

One way to verify if a function is present in an array is by using the Array.prototype.indexOf method:

var func1 = function () {};
var func2 = function () {};
var myArray = [];

var checkFunction = function (func) {
    if (myArray.indexOf(func) === -1) {
        myArray.push(func);
    }
};

checkFunction(func1);
checkFunction(func1);
console.log(myArray.indexOf(func1));    // outputs 0
console.log(myArray.indexOf(func2));    // outputs -1

Alternatively, you can utilize a map object to determine if a function has been added or not:

var funct1 = function funct1() {};
var funct2 = function funct2() {};
var myArr = [];
var myMap = {};

var addFunc = function (fn) {
    if (!myMap[fn.name]) {
        myArr.push(fn);
        myMap[fn.name] = fn;
    }
};

addFunc(funct1);
addFunc(funct1);
console.log(myArr.indexOf(funct1), myMap['funct1']);    // shows 0, function funct1() { ... }
console.log(myArr.indexOf(funct2), myMap['funct2']);    // shows -1, undefined

Note: This second approach may not be suitable for anonymous functions.

Answer №3

While compiling functions into the list, maintain a separate entity where you log a unique identifier to ensure whether the function has already been included in the array:

  var myList = [], functionLog = {};
  for (var x = 0; x < someLimit; ++x) {
     // carry out necessary actions
     if (certainCondition) {
       if (!functionLog[ "example code 1" ]) {
         myList.push(function() { /* example code 1 */ });
         functionLog[ "example code 1" ] = true;
       }
     }

     if (anotherCondition) {
       if (!functionLog[ "example code 2" ]) {
         myList.push(function() { /* example code 2 */ });
         functionLog[ "example code 2" ] = true;
       }
     }
  }

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

Interacting with YouTube Data API without requiring user input

I'm currently developing a music website that enables users to create YouTube playlists. Initially, I experimented with JavaScript: https://developers.google.com/youtube/v3/code_samples/javascript The procedure involves an initial authorization ste ...

How can I iterate through the lines of a JSON file using javascript?

I am currently working with JSON data and need to extract specific information based on an ID. For example, if the ID is 1, I want to retrieve details like service1 and version 1.0. I am looking to create a loop that will iterate through each line of data ...

Modify how the browser typically processes script tags as its default behavior

Most of us are familiar with the functionality of <script src="/something.js"></script>. This loads the specified file onto the page and executes the script contained within. Is there a way to modify how <script> elements are interpreted ...

Changing the color of a progress bar in Bootstrap based on a specific percentage level

var elem = document.getElementById("progress-bar"); var progress = 75; elem.style.width = 80 + '%'; if (progress > 80) { elem.style.background = "red"; } #myProgress { height: 5px; } #progress-bar { w ...

Determining if two numpy arrays are equivalent element-wise when containing floating point values

How can I determine if two numpy arrays are equivalent? Code: import numpy as np def numpy_equal(): x = np.array([2, 3, 1, 0.000000000000001000000000000000000000002]) y = np.array([2, 3, 1, 0.000000000000001000000000000000000000001]) #assert ...

Build an equilateral triangle with the power of three.js

I'm currently working on creating an equilateral triangle using three.js, but it seems like what I've created is a bit too tall. My vertices are defined as follows: new THREE.Vector3(0, 0, 0), new THREE.Vector3(4, 0, 0), new THREE.Vector3(2, 4, ...

What steps should I take to troubleshoot the 'TypeError: userId is not a function' error in my unban feature?

I am currently working on implementing an unban feature for my bot, however, I am encountering issues whenever I try to test the command (!unban <userId>). Instead of the expected outcome, I am faced with an error which is detailed below. This snipp ...

Stop a hyperlink from refreshing the webpage

Currently, I am in the process of developing a responsive menu. You can view a demo of my progress on Codepen. In order to prevent the page from reloading when I click a link within the menu, I have implemented the following JavaScript code: $('nav. ...

Updating or deleting query strings using JavaScript

My URL is structured as follows: http://127.0.0.1:8000/dashboard/post?page=2&order=title I am seeking a way to eliminate the query string ?page={number} or &page={number} Due to my limited knowledge of regular expressions, I am wondering if there ...

Transforming a matrix in LABVIEW into a grayscale image

I am currently working with the Mightex BTE-B050-U camera and have created a 2D array using LabVIEW based on the company's example. I would like to convert this array into a grayscale image, but I am unfamiliar with LabVIEW and encountering errors whe ...

What exactly is the functionality of the third parameter (usually next()) behind the scenes in ExpressJS once it is hidden behind the abstraction layer?

Consider this scenario: in the following two code snippets, how is the next() function used as a parameter and how does it facilitate the automatic transition to the next middleware function? What is the underlying mechanism that enables this abstraction? ...

Attempting to make initials fade and slide out upon mouseover using jQuery

I've been experimenting with jQuery to create a unique effect where hovering over my initials in the header expands the containing div and reveals my full name letter by letter. However, I'm facing some challenges and could use some guidance on t ...

Scrolling to the bottom of the page triggers jQuery to load additional content

Is your jQuery script not working properly when attempting to load more content upon reaching the bottom of the page? It seems to be functional on Safari/iPad and Android Mozilla browsers, but encountering issues on default Android and Chrome browsers. ...

Creating types for React.ComponentType<P> in Material-UI using TypeScript

I am currently working with Typescript and incorporating Material-UI into my project. I am trying to define the component type for a variable as shown below: import MoreVert from '@material-ui/icons/MoreVert' import { SvgIconProps } from '@ ...

Traverse a multi-level object or array using iteration techniques

There is information retrieved from a soap api, and it is structured in this way: array(2) { ["Request"]=> object(stdClass)#7 (3) { ["AccessKey"]=> string(3) "dub" ["Timestamp"]=> string(19) "2019.07.04 09:06:19" ["Conditi ...

Having issues with npm python-shell integration within electron framework

I'm currently attempting to establish a connection between a python script and an Electron app by utilizing the npm's python-shell package. The requirement is for the script to be executed whenever a button is clicked. So, let's assume my d ...

Why doesn't ngSubmit function inside a modal?

I am experiencing an issue where my submit button is not activating the ng-click angular directive, and I cannot seem to identify the cause. Most people who faced a similar problem did not have their submit button placed inside their form, but I am confi ...

Building interactive web forms with real-time validation using CodeIgniter

I'm looking for a way to use ajax (jquery library) to validate my forms. Specifically, I have a form that requires a minimum password length of 6 characters. Currently, I have implemented the validation rule as follows, $this->form_validation-> ...

Validate whether the path parameter in NextJS is null or empty before executing the query

Currently seeking a method to determine if the query value is empty using the path parameter approach. Have a file named pages/search/[variable1].js Below is the code snippet: import { useRouter } from "next/router" const Variable= () => { ...

Tips for swapping out a div tag with another div tag in the same spot without needing to redirect to a different page by utilizing bootstrap

Currently, I am developing a JSP project that utilizes Bootstrap for the frontend. I have come across a question regarding HTML design. Is there a way to replace one div tag with another div on the same page without navigating to a new URL using Bootstrap ...