I’m having trouble identifying the error. Is there a possible infinite loop happening somewhere?

// JavaScript Document
var person = prompt("ENTER INPUT", "");
var count  = 0;
var array  = person.split(",");
var freq   = [];
var words  = [];

// Commented lines removed for simplicity
var i = 0, j = 0;
while (array.length > 0) {
    var temp = array[0];
    while (j < array.length) {
        if (temp == array[j]) {
            count = count + 1;
            array.splice(j, 1);
            j = 0;
        }
        else {
            j = j + 1;
        }
    }
    freq[freq.length]   = count;
    count               = 0;
    words[words.length] = temp;
}
window.alert(freq + "\n" + words);

Encountering an infinite loop issue when running the code and unable to identify the error. Seeking assistance with debugging this JavaScript function designed to calculate word frequencies in a string input separated by commas. Thank you.

Answer №1

In order to make it work, simply place var i=0,j=0; within the while loop!

while(array.length>0)
{var i=0,j=0;

Check out this working demo

Answer №2

Every time the loop iterates, you are reassigning j to 0. Consequently, the condition if(temp==array[j]) will always evaluate to true, resulting in j being repeatedly reset to 0. As a result, the statement while(j<array.length) would continue to be satisfied indefinitely.

Answer №3

Upon exiting the inner While loop, it is crucial to reset the value of j back to zero. The current incremental value of j is preventing it from reentering the inner loop, causing array.length to remain the same and resulting in an endless loop.

// JavaScript Document
   var input = prompt("ENTER VALUES", "");
   var count=0;
   var array = input.split(",");
   var frequencies = new Array();
   var words = new Array();
   
   var i=0,j=0;
   while(array.length>0)
   {
   var temp=array[0];
   while(j<array.length)
   {
   if(temp==array[j])
   {
    count=count+1;
 array.splice(j,1);
 j=0;
   }
  else
  {
  j=j+1;
  }
  
   }
   frequencies[frequencies.length]=count;
   count=j=0;
   words[words.length]=temp; 
   }
   window.alert(frequencies+"\n"+words);

Answer №4

It's important to note that using for loop offers greater consistency in this situation. Instead of the inner while loop, you can achieve the same functionality with this for loop:

for(j=a.length-1; j>=0; j--)
    if(temp==a[j]) {
        count=count+1;
        a.splice(j,1);
    }

However, it may be beneficial to improve the complexity of your counting method by utilizing a data structure like a map.
You can simplify a significant portion of your script to the following:

var counter = new Map();
for (i in array)
    counter.set(array[i], (counter.get(array[i])||0)+1);
var freq = Array.from(counter.values());
var words = Array.from(counter.keys());

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

Setting field names and values dynamically in MongoDB can be achieved by using variables to dynamically build the update query

I am working on a website where users can place ads, but since the ads can vary greatly in content, I need to be able to set the field name and field value based on user input. To achieve this, I am considering creating an array inside each document to sto ...

JavaScript regex for the 'hh:mm tt' time format

I need to validate time in the format 'hh:mm tt'. Here is an example of what needs to be matched: 01:00 am 01:10 Pm 02:20 PM This is what I have tried so far: /^\d{2}:\d{2}:\s[a-z]$/.test('02:02 am') ...

Dependency on the selection of items in the Bootstrap dropdown menu

I am currently struggling with a few tasks regarding Bootstrap Dropdown Selection and despite looking for information, I couldn't find anything helpful. Check out my dropdown menu Here are the functions I would like to implement: 1) I want the subm ...

Populating dropdown menu with data from redux state upon component mounting

I am new to working with react-redux and have successfully implemented dependent dropdown functionality in a react component (Country => State => City). My goal now is to dynamically update the dropdown values based on data received from the redux s ...

Sort the array in alphabetical and numerical order while meeting a specific condition

In my code, I am attempting to sort an array based on two conditions. Specifically, I need to ensure that Pos 10 comes after single digits and follows a specific order after that. Initially, I tried to prioritize strings containing the word first, but whe ...

When switching tabs in Javascript, the page does not automatically reload. However, the page will reload only when it is on

After writing a code using javascript/Youtube API + PHP to fetch a YT video ID from a MySQL server and place it in Javascript, I realized that the page only reloads when the tab is active and not when it's in the background. This issue disrupts the wh ...

Every time you attempt to download in Vue, you are met with the familiar sight

Encountering a peculiar issue while attempting to download an apk file using a Vue.js website: Referring to How to download a locally stored file in VueJS, I am trying to download a local file with this command: <a href="../../app-debug.apk" download= ...

Having difficulty in setting items to a relative position in order to align them properly

I am struggling to align two div items next to each other using Bootstrap. This is for a product detail view where I want the image on the left and text on the right. It's a product detail page for an ecommerce site that I'm trying to create. May ...

Submitting an Ajax form to dual scripts

My goal is to pass variables from a single form to two separate php scripts for processing upon submission. The current setup that I have seems to be working fine, but I'm curious if there is a way to achieve this within one jQuery script instead of d ...

Exploring the JSON data in Javascript using Ajax

Completely new to Javascript, I am just trying to grasp the basics of the language. Currently, I have a JSON request set up with the following code: function request(){ $.ajax({ dataType: "jsonp", type: 'GET', url: "getWebsite", ...

Tips for toggling the visibility of a custom video-js component when the user is inactive

I am currently utilizing VideoJS with React and I have created a custom title bar component using the videojs-overlay feature. My goal is to make the title bar fade out when the user is inactive (not moving the mouse) and fade back in as they move the mous ...

Issue with collecting data in Meteor Collection

After making some edits to another file and increasing the complexity of my application, a tracker function that was previously working fine is now experiencing issues. It is no longer returning any data for vrLoan fundingData This is a snippet of my c ...

React - How to Close Material-UI Drawer from a Nested Menu

Currently, I am utilizing a fantastic example (here) to create a dynamic nested menu for my application. Taking it a step further, I am trying to integrate it into a Material UI appbar/temporary drawer. My goal is to close the drawer when the user clicks o ...

Exploring JSON data with multiple nested layers of iteration

I'm currently working on a project that involves parsing through a JSON file with a complex structure. I've been attempting to extract a link to an image within the JSON data, but my current approach is resulting in an error. Below you'll fi ...

What is the solution to the error message "Cannot assign to read only property 'exports' of object '#<Object>' when attempting to add an additional function to module.exports?"

I've been struggling for the past 5 days with this issue. Despite numerous Google searches, I haven't found a solution that works for me. I have a file called utils.js which contains useful functions to assist me. However, when I include the func ...

Transferring a CSV file to the server from a React application using multi-part form

In order to post a CSV file to an API using React, I have attempted to do so in multipart form. While many tutorials and websites suggest using the fetch() method for sending files to a server, I am encountering some challenges. The issue lies with my RES ...

Transfer the information from dropped files in a div to a separate page

document.getElementById('drag_drop').ondrop = function(event) { event.preventDefault(); var form_data = new FormData(); var drop_files = event.dataTransfer.files; for(var count = 0; count < drop_files.length; count++) ...

Encountering a CSS issue during the edit process with PHP and JavaScript

I'm encountering an issue when clicking on the edit button, as my data fetched from the DB should be displayed inside a text field. However, I'm facing a CSS-related error: Uncaught TypeError: Cannot read property 'style' of null Belo ...

Trouble with formatting a HTML form

I have been working on dynamically creating HTML forms using a function called makeInput(). However, I am facing an issue where the text input boxes are appearing next to each other when I click the "Add Course" button, instead of one per line. Below is ...

Issue with Gulp and Browserify task: Why is there no output?

I've set up the following task in my gulpfile.js gulp.task('default', ['browserify']) gulp.task('browserify', function () { return browserify('./public/js/x.js') .bundle() .pipe(source('y.js& ...