Trouble with second function invocation in JavaScript

After creating two sets of arrays and passing them into different functions, I noticed some strange behavior. The first time I called the functions for scores1, everything worked perfectly. Likewise, the second time I called the first function (for Scores2), it also worked without any issues. However, things took a bizarre turn when I called the second function again for Scores2. It started displaying results from the previous call for Scores1 instead. Even more puzzling was that it recognized only two high scores instead of three, but somehow managed to pick them from the other array.

Any help or insight on this matter would be greatly appreciated,

Rob.

var scores1 = [20, 40, 44, 50, 66, 56, 44, 69, 69, 65, 45, 56, 67, 55, 45, 32, 49, 59, 60, 62, 65, 55, 66, 69, 57, 68, 66, 61, 65];

var scores2 = [31, 60, 44, 55, 66, 56, 44, 69, 69, 65, 45, 56, 67, 55, 74, 32, 49, 59, 60, 62, 65, 74];

function printAndGetHighScore(scores) {
  var highScore = 0;
  var output;
  for (var i = 0; i < scores.length; i++) {
    output = "Bubble solution #" + i + " score: " + scores[i];
    console.log(output);
    if (scores[i] > highScore) {
      highScore = scores[i];
    }
  }
  return highScore;
}

function getHighestScores(scores) {
  var highestScores = [];
  for (var i = 0; i < scores.length; i++) {
    if (scores[i] == highScore1) {
      highestScores.push(i);
    }
  }
  return highestScores;
}

var highScore1 = printAndGetHighScore(scores1);
console.log("Bubble tests: " + scores1.length);
console.log("Highest bubble score: " + highScore1);
var highestScores1 = getHighestScores(scores1);
console.log("Highest scoring solutions: " + highestScores1);

var highScore2 = printAndGetHighScore(scores2);
console.log("Bubble tests: " + scores2.length);
console.log("Highest bubble score: " + highScore2);
var highestScores2 = getHighestScores(scores2);
console.log("Highest scoring solutions: " + highestScores2);

Answer №1

In order to avoid errors, make sure to define highScore1 before calling the getHighestScores function as it is used as the comparison score throughout the function. Additionally, when trying to challenge a high score, pass it in as a second parameter like shown below:

function getHighestScores(scores, highestScore) {
    var highestScores = [];
    for (var i = 0; i < scores.length; i++) {
      if (scores[i] >= highestScore) {
      highestScores.push(i);
    }
  }
  return highestScores;
}

To call the function, use the following format:

var highScore1 = printAndGetHighScore(scores1);
console.log("Bubble tests: " + scores1.length);
console.log("Highest bubble score: " + highScore1);
var highestScores1 = getHighestScores(scores1,highScore1);
console.log("Highest scoring solutions: " + highestScores1);

var highScore2 = printAndGetHighScore(scores2);
console.log("Bubble tests: " + scores2.length);
console.log("Highest bubble score: " + highScore2);
var highestScores2 = getHighestScores(scores2,highScore2);
console.log("Highest scoring solutions: " + highestScores2);

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

Tips for accessing the firebase user's getIdToken method in Next.js after a page reload

Currently, I am developing a Next.js project and implementing user authentication using Firebase's signInWithPhoneNumber method for phone number verification. After successful verification, I receive a Firebase user with the getIdToken method to retri ...

The console log is displaying 'undefined' when trying to access Node.js fs

Recently, I was engrossed in developing a Next.js blog. After completing the frontend, I shifted my focus to building the backend using Next.js. ./pages/api I created a new file: ./pages/api/blogs.js To test my backend functionalities, I generated some J ...

What is the best way to prevent a folder from being included in the next js build process while still allowing

I am faced with a challenge involving a collection of JSON files in a folder. I need to prevent this folder from being included in the build process as it would inflate the size of the build. However, I still require access to the data stored in these file ...

Having trouble finding the correct output when searching in the table using regex

I am currently experiencing an issue with my code for searching. When I search the full text, it works fine but when I search for a middle character, it does not work as expected. For instance, searching for "apple" or "ap" works correctly, however, if I ...

The tooltips in the WordPress-Gulp-Starter-Kit running on Bootstrap 5 do not seem to be functioning properly

I'm having trouble with tooltips not working properly. The codebase I'm using is from this repository https://github.com/oguilleux/webpack-gulp-wordpress-starter-theme If you need more details, feel free to reach out. Here is my main.js file: ...

jQuery failing to append code after being removed

I need some assistance with an issue I've run into while using jQuery's .remove(). Here is a snippet of code that showcases the problem: $( '.video-button span.glyphicon-play' ).click(function() { $( '#video-player' ).ap ...

If the if logic in Express.js fails to function properly, it will consistently output the same message

Every time I run this code, it always displays the same message, even when I input different email addresses let message = ""; const findQuery = "select email from Users where email = ?"; const queryResult = await db.query(findQue ...

Tips for Creating and Verifying JWE in Node.js

I attempted to use the following code in order to create an RSA-OAEP and A128GCM JWE generator and validator. It successfully encrypts claims and generates the JWE, then decrypts it and provides me with the original claims when running on node.js. However, ...

Extending a Sub-Object in JavaScript

I'm attempting to include new attributes to the sub-object within object1. However, I am facing issues with it being overwritten. const object1 = { a: 1, b: 2, c: 3, sub: { e: 1, f: 2 } }; const object2 = Object.assign({ j: 4, ...

"Learn the process of sending a post request using a combination of JQuery, Ajax

I am attempting to send a post request with the following code - var app = angular.module('myApp', []); app.controller('myCtrl', function ($scope) { $scope.data = {}; $scope.reqCalling = function () { ...

Using a promise instead of resolving it with Angular's $q.then() methodology

Imagine you come across the given code snippet: var callNo1 = $http(...).then(function (response1) { var callNo2 = $http(...).then(function (response2) { return [response1.data, response2.data]; }); return callNo2; }).then(function (r ...

Tips on retrieving an input value from a dynamic list

I am struggling to retrieve the correct value with JavaScript as it always shows me the first input value. Any help would be greatly appreciated! Thank you in advance! <html> <head> </head> <body> <?php while($i < $forid){ ...

Encountering a FeathersJS Twitch OAuth 401 Unauthorized error

I'm a newcomer to FeathersJS and I've been trying to set up OAuth login with Twitch. Following the steps outlined in the Feathers documentation for setting up GitHub login OAuth, I created a Twitch OAuth application. However, when attempting to s ...

Experiencing memory issues with small programs in Node on macOS?

Currently, I am in the process of learning JavaScript and making use of node to execute JS programs directly from the terminal using this command: node program1.js The issue that I am encountering involves a simple JavaScript program that is supposed to ...

Control the options of the Select menu using ajax

Consider having two dropdown menus <select id=first> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</opti ...

Adding a placeholder to a MUI Select component with different value prop and MenuItem options: a step-by-step guide

Is there a way to include a placeholder (-- Select --) in the MUI Select component below? const [country, setCountry] = useState("") <FormControl fullWidth error={!country}> <Select displayEmpty renderValue={selected => sel ...

Here's a guide on how to package and send values in ReactJs bundles

I'm currently involved in a ReactJs project that does not rely on any API for data management. For bundling the React APP, we are using Webpack in the project. The challenge now is to make the React APP usable on any website by simply including the ...

What is the clarification on AngularJs' ng-options?

In my demo, I have a small setup. Essentially, it consists of a select element with the following data: address: { select: { code: "0", name: "Select proof of address" }, letter: { ...

Typescript allows you to apply a filter to an array

Query: Is there a way to display a pre-selected item from my dropdown using its unique ID? Issue/Explanation: The dropdown options in my web service are dynamically fetched based on a user's ZipCode. For example, a Provider is displayed as {Pho ...

What is the best approach to determine the value of a textbox in an array for each row of

I am trying to display the total sum of values for each row in a data array. There are 5 rows of data, and I need to calculate the results for each one. Can someone assist me in solving this? function calculateTotalValue(){ var total = (document.get ...