Is there a way to utilize a switch statement in JavaScript to determine the quantity of numerical elements within an array?

I am attempting to use a switch statement in my function to count the number of elements (numbers only) in an array. However, I am uncertain about how exactly the code should be structured. This is what I have managed to come up with thus far:

<script language="JavaScript">
//array containing numbers
var numbers = [1,"o",2,3,"a",0];
//implementing a switch statement

switch (numbers) {
    //I am unsure of the syntax to use here....

    break;
}
  //output result of the count
alert(count)
</SCRIPT>

Answer №1

using a switch statement

if you insist:

let counter = 0;
for( let index=0 ; index<numsArray.length ; ++index )
    switch( typeof(numsArray[index]) ) {
        case "number": ++counter; break;
    }

counter now holds the value of 4.

Note: NaN, Number.NEGATIVE_INFINITY, and Number.POSITIVE_INFINITY are also considered as "number"s, so if you need to exclude them from the count, use this modification:

let counter = 0;
for( let index=0 ; index<numsArray.length ; ++index )
    switch( typeof numsArray[index] ) {
        case "number":
            if( !isNaN(numsArray[index]) && isFinite(numsArray[index]) )
                ++counter;
    }

Answer №2

I find the existing answers to be quite lengthy and inefficient.

Here is my approach, utilizing the .reduce method:

var numbers = [1,"o",2,3,"a",0];

var count = numbers.reduce(function(accumulator,current){
    return accumulator + (typeof current === "number");
});

Another option involves incorporating a necessary switch:

var numbers = [1,"o",2,3,"a",0];

var count = numbers.reduce(function(accumulator,current){
    return accumulator + (typeof current === "number");
    switch(true){} // This switch statement is named Alfred, inspired by Batman's loyal butler.
});

Answer №3

let array = [1, "b", 2, 3, "x", 0];
let count = 0;
for(let j = 0; j < array.length; j++){
    if(typeof array[j] === "number") count++;
}
console.log(count);

Answer №4

Update: Sure thing! Let's implement a switch statement!

var count = 0;
for(var i = number.length; i--;){
    switch(true){
        case typeof number[i] == 'number':
            count++;
    }
}
alert(count);

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

Error: Service Liferay encountered an unexpected identifier causing a syntax error

Upon clicking on the button labeled "delete save" in the Chrome console, an error is encountered: "Uncaught SyntaxError: Unexpected identifier". Additionally, when this action is performed, an object is printed to the console revealing its data ({company ...

Unable to configure AngularJS inputs to have a blank default value

I am facing a peculiar issue where I am unable to initialize my input fields as blank/empty. Even after clearing the cache and performing a hard reload, Google Chrome seems to be auto-populating them with older cached values. Here is the current view: ht ...

Implementing the same logic across multiple multidimensional arrays is paramount

Currently, I am experimenting with the following scenario: I have several arrays that are populated by data fetched from a database. While they all have the same columns and data structure, they contain different information. For example, imagine the arra ...

incorporating numerous interconnected javascript files within a single html document

I have a pair of JavaScript files (file1, file2). File1 utilizes a class that is defined in file2. Can I include these files in an HTML document like this: <script type="text/javascript" src="file1.js"></script> <script type="text/javascrip ...

Highlighting with pretty JSON formatting

Is there a way to format JSON on a website and emphasize certain text or lines within it? Ideally, I'm looking for an IFRAME service that I can link to a URL where the JSON is downloaded and displayed as HTML. I want to be able to specify a search st ...

Is there a workaround for making Three.js OnDocumentMouseDown compatible with touch screens?

To view the complete code, visit this Glitch project: Within public/components.js, I have defined a custom AFRAME component that enables rotation of an item when dragged with the mouse. AFRAME.registerComponent('drag-rotate-component', { sc ...

Deleting a row from a Material UI table: Step-by-step guide

I'm currently working on a CRUD table using React and Material-UI. I have successfully fetched data from an API and displayed it in a table, but now I am facing a challenge with deleting a row. As this is my first project in React, I am seeking guidan ...

What is the target of the `__proto__` attribute in a constructor function?

I'm taking the time to dive deeper into prototypal inheritance. I know that an instance's __proto__ property points to the constructor function's prototype object, but where does the constructor function's __proto__ property point to? ...

There was an uncaught error in AngularJS stating that the URL in the HTTP request configuration must be a string

I've been working on a web application and have encountered some challenges. One particular issue I'm struggling with is related to the following code snippet: this.bookSpace = function (date, spaceId) { swal({ title: "Are you sure?", t ...

In Swift 3, there is a strange occurrence where the UICollectionView seems to repeat the final cell multiple

In order to create a chat log controller, I am populating a message array with all the messages received from a chatroom chat SDK. The array is defined as: var messages = [Message](). To achieve this, I have implemented the following function: func obser ...

Tips for preventing the need to convert dates to strings when receiving an object from a web API

I am facing an issue with a class: export class TestClass { paymentDate: Date; } Whenever I retrieve an object of this class from a server API, the paymentDate field comes as a string instead of a Date object. This prevents me from calling the ...

The jQuery hover function is not functioning properly on page load in Firefox

While this code is functioning smoothly in Chrome and IE, it seems to be encountering issues in Firefox! <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> JS: $(window).load(function(){ $("#bosti ...

Discovering the Nearest Element in an Array: A Step-by-Step Guide

I've been searching for the solution to this problem without much success. The task involves creating the Fibonacci Code and then allowing a user input to search for their input in the sequence. If the number is in the sequence, it will display the in ...

Performing automatic submission of form data without needing to redirect or refresh the page using Javascript

I am trying to find a way to automatically submit form post data without the page redirecting, but I haven't had success with any of the examples I've found that involve jquery and ajax. Currently, my code redirects the page: <!DOCTYPE html& ...

How can I use a dropdown with checkbox to toggle the visibility of a specific div in React?

I have come across a relevant question, but I am struggling to apply it to multiple divs. I haven't found a solution that quite fits my needs. Show or hide element in React Currently, I am using the dropdown with checkboxes from MUI. I am seeking a ...

What is the best way to show "no results found" message in a jQuery search list?

Everything is working smoothly. Does anyone have any suggestions on how to display a message saying "No results found"? This is the code I'm using: http://jsfiddle.net/UI_Designer/8p426fog/4/ $(".my-textbox").keyup(function() { var val = $( ...

Positioning of dropdown in Material UI select component

Unfortunately, I am encountering an issue with the Menuprops attribute and cannot seem to adjust the position of the drop-down box. Despite following the instructions from other similar queries, the desired outcome remains unachieved. My goal is to have t ...

Setting up an array using a pointer followed by retrieving information from it

I encountered an issue with a program written in C++. It involves using a pointer to initialize an int array and then reading the data back. However, instead of getting integer values, the output consists of random letters and digits. I am unable to pinpoi ...

Determining the sum of each third element in a Java array

Initially, I had a String array called FileContent, which I then converted into an ArrayList named MatchingContent. The String FileContent contains: "2017-04-03, 11:25, 2; 2017-04-02, 11:30, 8; 2017-04-03, 14:42, 9". My goal now is to iterate through eve ...

Optimizing PHP Class for Enhancing Array Performance

I have a snippet of code that allows me to update an array with one value at a time. I am looking to modify this code so that I can update the array with multiple values in one function call, like this: $var->updateArray("Value 1", "Value2", "Value 3", ...