What is the method for determining the number of arrays contained within a file?

I am working with a JavaScript file that looks like this:

// main.js

let array1 = ['first array'];
let array2 = ['second array'];
     

Currently, I have two arrays declared in my main.js file. Is there a method to determine the total number of arrays present within the file?

Answer №1

One method to accomplish this is...

Object.keys(window).forEach( (key) => { 
  if (Array.isArray( window[key] )) { 
      console.log(`${key} is an array`);  
  } 
});

It's important to note that this approach is designed for global objects specifically (i.e., objects associated with the window global variable).

Update: In response to a suggestion from @Mhmdrz_A's comment, an alternative is to create a function that evaluates an object for the presence of arrays:

function getArrayCount(object) {
   let count = 0;
   Object.keys(object).forEach( (key) => { 
      if (Array.isArray( object[key] )) { 
          count += 1;  
      } 
    });
    return count;

}

let anyObject = { someArr: [], anotherArray: [], yetAnother: []};

console.log(getArrayCount(anyObject)); // 3

However, this method only checks the top layer of properties for the specified object. To thoroughly examine each property for nested arrays, a recursive evaluation is necessary.

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

Ways to dynamically fetch data by merging the response outcome with a dynamic parameter from the route in Vue.js

For the first time, I have been tasked with dynamically retrieving object parameters from the URL parameter. I am aware that I can use this.$route.params.[somelink-parameter] to obtain the URL parameter, and I understand how to retrieve and store the respo ...

The combination of React.js and debouncing on the onChange event seems to be malfunctioning

I recently incorporated a React component that triggers an event on change. Here's how I did it: NewItem = React.createClass({ componentWillMount: function() { this._searchBoxHandler = debounce(this._searchBoxHandler, 500); }, _searchBoxH ...

Strategies for navigating dynamic references in Angular 2 components

I am working with elements inside an ngFor loop. Each element is given a reference like #f{{floor}}b. The variable floor is used for this reference. My goal is to pass these elements to a function. Here is the code snippet: <button #f{{floor}}b (click) ...

Executing a function in AngularJS using PHP

My current project involves an Angular application that needs to load a PHP page within the view. The setup is functioning properly, but I now require an Angular function to run after the PHP code has loaded. I am wondering about the process of calling an ...

Confusion between modules and classes in Node.js when using CoffeeScript

I'm struggling to understand how to use Protoype in CoffeeScript, even though I am familiar with using it in standard Javascript with Node.js and modules. Imagine I have a file named mymodule.coffee: Module = {} class MyModule constructor: (para ...

Automated user roster refresh

I have an online user list that is dynamically generated using a SQL query on a database table. How can I implement real-time updates to the webpage when a new user logs in? What specific code do I need to include for this functionality? Appreciate any g ...

Issues with Express js routing functionality and executing mysql queries

As I dive into learning Node and Express, I'm encountering issues with routing in Express. I aim to create a well-organized and modular code for handling routes, particularly when querying data from a MySQL database: Let's start with my app.js f ...

Error with Laravel and Vue template integration

I have recently started using Vue in Laravel 5.3 and I am able to retrieve data through a jQuery AJAX request within Vue. However, I am facing difficulties with displaying the data. Below is my current script in the view: <li> <!-- inner men ...

Can the state and city be filled in automatically when the zip code is entered?

I have a form where users can enter their zip code, and based on that input, the corresponding city and state will automatically populate. These three fields are positioned next to each other within the same form. Here is an example of my form: $(' ...

Is there a way for me to verify if I have already made an AJAX data request

I have an image gallery with thumbnails. When a user clicks on a thumbnail, an ajax request is fired. I want to prevent the ajax request from firing again if the user clicks on the same thumbnail and instead use the existing data. $.getJSON(url, function( ...

The hyperlink element is failing to load in a particular frame

I've been attempting to load the URL of an anchor tag in a specific frame. I've tried various methods through online searches, but have not found a satisfactory solution. Can someone please assist me with how to load the href URL in a particular ...

NodeJs Classes TypeError: Unable to access 'name' property as it is undefined

I am currently developing a useful API using Node.js. In order to organize my code effectively, I have created a UserController class where I plan to include all the necessary methods. One thing I am struggling with is how to utilize a variable that I set ...

Errors in Compiling Dependencies for d3.js Using Typescript

Currently, I am in the process of developing a web application utilizing Node.js alongside Angular, Typescript, and d3.js, among other technologies. The application is functioning properly with library features working as expected. However, I am encounteri ...

How can I prevent the arrow keys and space bar from causing my webpage to shift downwards?

I created a game where the arrow keys control movement and the space bar shoots, but every time I press the down key or space bar, it scrolls to the bottom of the web page. Is there a way to adjust the CSS so that it focuses on the game div tag without ...

My PHP errors and success messages are not being displayed properly after an AJAX success

After making an AJAX call to submit a form, I would like to display either the PHP success message or error message upon completion. This is my current AJAX success function: success: function (data) { resultSuccess = $(data).find("#success") ...

I'm having trouble with installing nx as it keeps showing the error message 'Platform Dependency for NX is Missing.'

I encountered an issue when running npm install: $ npm i npm WARN deprecated @babel/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b5b475e4c4245065b59445b44584a470648474a5858065b59445b4e595f424e586b1c051a13051d">[email  ...

Tips for applying stroke and shadow effects specifically when the mouse is moving over a canvas:

How can we create a shadow and stroke effect for circles drawn using HTML canvas only during mouse hover? I have two circles and would like to add a shadow and stroke effect when the mouse hovers over them. However, the issue is that once the mouse moves ...

Currently I am developing a Minimax Algorithm implementation for my reversi game using react.js, however I am encountering a RangeError

I've been implementing a Minimax Algorithm for my reversi game to create a strong AI opponent for players. However, I ran into the following error message: "RangeError: Maximum call stack size exceeded" How can I go about resolving this issue? Here ...

When conducting tests using Selenium and the headless Google Chrome browser in Java, the dynamic JS content fails to load

Currently, I am in the process of testing a website that I have developed as part of a Spring Boot project using Selenium. While I can successfully test basic functionalities such as page loading and title verification, I am encountering difficulties when ...

Having trouble accessing a PDF file using gview

Having trouble opening a document I am unable to preview the documents and I'm not sure what I'm missing. I have read through various StackOverflow questions and answers related to this issue, but still no luck. url = http://192.168.0.6:8077/ ...