How do I display the frequency of a number occurring multiple times within an array in JavaScript?

I'm currently working on this task:

Create a JavaScript function that prompts the user for a number and then displays how many times that number appears in an array.

To achieve this, I am using parseFloat to convert the user input from a string to a number. I have also defined my own array with a set of numbers.

function repeatNumber() {
  const number = parseFloat(document.getElementById("number").value);
  const myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  let compare = false;
  let count = 0;
  for (let i = 0; i < myArray.length; i++) {
    if (myArray[i] === number) {
      compare = true;
      count++;
    }
  }

  //compare is where the result will be displayed
  const repeating = document.getElementById("compare");

  repating.textContent = "Is your number in my array ?" + compare;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0>
    <script src="/controlFlow/script.js"></script>
    <title>Js>
</head>
<body>
    <label for="number">Please enter a number to check its presence in my array</label>
    <input type="text" id="number">
    <button onclick="repeatNumber()">Check</button> 
    <p id="compare">  </p>
  
</body>
</html> 

Answer №1

Here's a suggestion for you to try out:

function checkNumberPresence() {

  const inputNumber = parseFloat(document.getElementById("number").value);
  const myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  let isPresent = false;
  let count = 0;

  for (let i = 0; i < myArray.length; i++) {
    if (myArray[i] === inputNumber) {
      count++;
      isPresent = true;
    }
  }
  const resultElement = document.getElementById("compare"); // 'compare' is the id of the paragraph element where the result will be displayed
  resultElement.textContent = "Is your number in my array? " + isPresent;
  console.log(count);
}

Answer №2

function countOccurrences() {
        const numbersArray = [3, 6, 9, 12, 15, 18, 21];
            const userInputValue = document.getElementById("number").value;
            const numberToFind = parseInt(userInputValue);
            if (!isNaN(numberToFind)) {
                const occurrencesCount = numbersArray.reduce((acc, val) => {
                    return val === numberToFind ? acc + 1 : acc;
                }, 0);

                const displayResult = document.getElementById("result");
                displayResult.textContent = `Is your number present in my array? ${occurrencesCount} times`;
            } else {
                alert("Invalid input. Please enter a valid number.");
            }
        }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="/controlFlow/script.js"></script>
    <title>JavaScript Example</title>
</head>
<body>
    <label for="number">Enter a number to check its presence in the array:</label>
    <input type="text" id="number">
    <button onclick="countOccurrences()">Check</button> 
    <p id="result"></p>
  
</body>
</html>

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

Is there a way to instantly remove script from the document head using jQuery instead of waiting a few seconds?

I currently have a setup where I am utilizing Google Maps in production. To make this work, I must include a script in the head of my document that contains the API key for the Google Maps JavaScript API that my application relies on. The API key is being ...

SailsJs: Model.find().exec() can sometimes generate unexpected properties

I recently created a service function in api/services/SomeServices.js getCreditDebitNotes:function(vid){ console.log('resolving credit and debits'); var deferred=sails.q.defer(); CreditDebitNotes.find({vendorID:vid,status:1},{selec ...

React Native animation encountered a rendering issue: Invalid transform scaleDisliked value: { "scaleDisliked": 1 }

While working on my react native app, I encountered an issue when trying to apply a transform:scale effect to an Animated.View component. I am using interpolate for this purpose, but unfortunately, I keep receiving the following error message: Render error ...

Validating data with Joi can result in multiple error messages being displayed for a single field

I'm attempting to implement a validation flow using the joi package, which can be found at https://www.npmjs.com/package/joi. 1) First, I want to check if the field category exists. If it doesn't, I should display the error message category requ ...

The user's input is not being accurately represented when making an AJAX request to the

When attempting to incorporate a user's city input (e.g. Los Angeles) into Ajax URL parameters, there seems to be an issue where the '+' is not being added between "los angels", resulting in a broken URL when console.log(searchURL) is used. ...

Strategies for deploying on production as you develop a fresh Nuxt application

What are some recommended strategies for deploying a Vue/Nuxt project on production, especially for larger applications with lengthy build times? Typically, running the command npm run build Causes the app to be inaccessible to users until the build proc ...

Utilizing a series of linked jQuery functions

Is there a more efficient way to write this code snippet? $('#element').html( $('#element').data('test') ); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="el ...

Avoid making GET requests when clicking on a link

[UPDATE] I need help troubleshooting an issue with my ajax request. Here is the code snippet that I am working on: <a href="" class="undo_feedback">Undo</a> When I click on the link, it triggers an ajax POST request, but I encounter an error ...

Looking to enhance code by using jQuery to substitute numerous href elements. Only seeking enhancements in code quality

I am currently using regular JavaScript to change the href of 3 a-tags, but I want to switch to jQuery for this task. var catNav = $('ul.nav'), newLink = ['new1/','new2','nwe3/']; catNav.attr('id','n ...

Animations do not trigger with content changes in AngularJS ngIf

According to the Angular documentation on ngIf, animations occur just after the contents change and a new DOM element is created and injected into the ngIf container. Animations In my experience, I have encountered issues with this behavior. To demonstra ...

Is there a reason why this jquery is not functioning properly in Internet Explorer 8?

Seeking assistance to troubleshoot why this jQuery code is not functioning properly in IE8. It performs well in Chrome but encounters issues in IE. $(document).ready (function() { $('.first-p').hide(); $( "div.first" ).click(function() ...

Initiate a Gravity Forms form refresh after modifying a hidden field with jQuery

TO SUM IT UP: Is there a way in Javascript to activate an update on a Gravity Form that triggers the execution of conditional logic? ORIGINAL QUESTION: I'm using Gravity Forms and I have set up an "on change" event $('#gform_1').find(&apos ...

Managing dynamically appearing elements in Ember: Executing a Javascript function on them

I'm currently working on a project in Ember and facing an issue with calling a JavaScript function when new HTML tags are inserted into the DOM after clicking a button. Below is a snippet of my code: <script type="text/x-handlebars" id="doc"&g ...

Implementing Window.Open function within a jQuery Modal

I've set up my Modal Div like this: <div id="dialog-modal" title="Open File"> <img alt="progress" src="images/ajax-loader.gif"/> </div> When I click the button, the modal appears and I can see the progress icon. <sc ...

Manipulate the DOM to remove a checkbox using JavaScript

I'm brand new to exploring the world of Javascript and could use some guidance with this task. I have a collection of checkboxes that I'd like to manipulate so that when one is checked, it disappears from the list automatically. I've come ac ...

Creating an Array of Objects

I was on the hunt for a way to modify the size of an array of Objects, but unfortunately my search was fruitless. I have two classes, Main and Element. Element is structured as follows: public class Element { int posX,posY; int eleme ...

Trouble getting a sticky element to align with a two-column grid within a parent container

I'm looking to keep one column sticky in a two-column grid setup. My goal is to create a vertical navigation bar that's specific to a particular div within a single-page site, with a fixed horizontal navbar across the entire page. However, I&apos ...

What is the best way to stack several elements on top of each other?

<div class="parent"> <div class="child" id="child-A"> <div class="child" id="child-B"> <div class="child" id="child-C"> </div> The main concept here ...

Add buttons to images to provide further explanations

While browsing the Excel Learn website, I came across a picture that displayed buttons explaining various functions in Excel. By clicking on the picture, a menu would open up to further explain the corresponding button. If you want to see this in action, ...

Struggling to display or transmit information from middleware in Node.js

I currently have an express server running on port 8082. When I access the route "/" as a GET request, it renders the index.html file. Then, I submit its form to "/" as a POST request using the app.js script. This route contains a middleware named "validat ...