Bizarre JavaScript Comparisons

I encountered an issue with the comparison process. The expected result should be 11 since the cost of the product at index 11 is lower than the cost of the product at index 18. However, the computed result turns out to be 18.

    var scores = [60, 50, 60, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 61, 46, 31, 57, 52, 44, 18,
    41, 53, 55, 61, 51, 44];
    var costs = [.25, .27, .25, .25, .25, .25, .33, .31, .25, .29, .27, .22, .31, .25, .25, .33, .21, .25, .25, .25, .28, .25, .24, .22, .20, .25, .30, .25, .24, .25,
        .25, .25, .27, .25, .26, .29];
//TOTAL, HIGHEST, INDEX OF THE HIGHEST
function findMaxIndex(array,arrayCost){
    var maximum=Math.max(...array);
    var arrayIndex=[];
    for(var i=0;i<array.length;i++){
        if(array[i]==maximum){
            arrayIndex.push(i)
        }
    }

   var minimum=arrayCost[arrayIndex[0]];//0.22
   for(var i=0;i<arrayIndex.length;i++){
       if(arrayCost[arrayIndex[i]]<=minimum){//0.25>=0.22
           minimum=arrayIndex[i];
       }
   }
    return minimum;
}

Answer №1

Upon entering the second if condition, you update the value of minimum to 11 by assigning it the value of arrayIndex[i]. Consequently, in the subsequent loop iterations, the minimum will remain at 11, causing arrayCost[arrayIndex[i]] to be less than 11. To address this issue, consider creating a new variable to store the index value.

function findMinimum(array, arrayCost) {
  var maximumValue = Math.max(...array);
  var arrayIndex = [];
  
  for (var i = 0; i < array.length; i++) {
    if (array[i] == maximumValue) {
      arrayIndex.push(i);
    }
  }

  var resultIndex = arrayIndex[0];
  var currentMinCost = arrayCost[arrayIndex[0]]; //0.22
  
  for (var i = 0; i < arrayIndex.length; i++) {
    if (arrayCost[arrayIndex[i]] <= currentMinCost) {
      currentMinCost = arrayCost[arrayIndex[i]];
      resultIndex = arrayIndex[i];
    }
  }
  
  return resultIndex;
}

Answer №2

The bug you are facing is visible in the comments, however, I suggest reworking it to optimize with a single loop:

var scores = [60, 50, 60, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 61, 46, 31, 57, 52, 44, 18,
    41, 53, 55, 61, 51, 44];
    var costs = [.25, .27, .25, .25, .25, .25, .33, .31, .25, .29, .27, .22, .31, .25, .25, .33, .21, .25, .25, .25, .28, .25, .24, .22, .20, .25, .30, .25, .24, .25,
        .25, .25, .27, .25, .26, .29];


function index(array, arrayCost) {
  var maxScore = Math.max(...array);
  var minCostIndex = null;
  for (var i = 0; i < arrayCost.length; i++) {
    if (array[i] != maxScore) {
      continue;
    }
    if (minCostIndex == null || arrayCost[i] < arrayCost[minCostIndex]) {
      minCostIndex = i;
    }
  }

  return minCostIndex;
}

console.log("res", index(scores, costs));


To enhance efficiency further, you can even remove the Math.max function call:

var scores = [60, 50, 60, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 61, 46, 31, 57, 52, 44, 18,
    41, 53, 55, 61, 51, 44];
    var costs = [.25, .27, .25, .25, .25, .25, .33, .31, .25, .29, .27, .22, .31, .25, .25, .33, .21, .25, .25, .25, .28, .25, .24, .22, .20, .25, .30, .25, .24, .25,
        .25, .25, .27, .25, .26, .29];


function index(array, arrayCost) {
  var maxScore = array[0];
  var minCostIndex = 0;
  
  // start iteration at 1, as 0 is already considered
  for (var i = 1; i < arrayCost.length; i++) {
    if (array[i] > maxScore) {
      maxScore = array[i];
      minCostIndex = i;
      continue
    }

    if (array[i] == maxScore && arrayCost[i] < arrayCost[minCostIndex]) {
      minCostIndex = i;
    }
  }

  return minCostIndex;
}

console.log("res", index(scores, costs));

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

Using jQuery's append function will retrieve external source files within script tags, however, it will not officially render them in the DOM

After including a script with an external source and attempting to parse it using jQuery, the script is downloaded but not loaded into the DOM. This issue persists regardless of which jQuery DOM insertion method I use, such as .append(). Take a look at th ...

Manipulate your table data with jQuery: add, update, delete, and display information with ease

When adding data dynamically to the table and attempting to edit, the checkbox value is not updating. This issue needs to be resolved. You can view the code in action on jsFiddle here on JSFiddle ...

The modification of HTML styles

How can I change the style (width, color etc) of all 8 functions like this? function my(){document.getElementById("question1").innerHTML="THIS QUESTION"+ "<br>" +"<button onclick=answer1() id=ques1 >first answer</button>" +"<button ...

Mobile phone web development using HTML5

I am currently facing an issue with playing sound on mobile browsers. In my code snippet, I have the following: Response.Write("<embed height='0' width='0' src='Ses.wav' />"); While this works perfectly fine on desktop ...

Creating a file logging system with console.log() in hapi.js

I have recently developed an Application with Hapi.js and have utilized good-file to record logs into a file. However, I am facing an issue where the logs are only written to the file when using request.log() and server.log() methods. My goal is to also lo ...

React Hook Form: Reset function triggers changes across all controllers on the page

I encountered an issue with using the reset function to clear my form. When I invoke the reset function, both of my form selects, which are wrapped by a Controller, get cleared even though I only defined default value for one of them. Is there a way to pr ...

Tips for updating an element in an array by using another element from a separate array

What is the objective? We have two arrays: orders and NewOrders We need to check for any orders with the same order_id in both arrays. If there is a match, we then compare the order status. If the order from the NewOrders array has a different status, w ...

Transferring information to a subordinate view

I'm working on developing a single-page application and need to transfer data to a child view. After fetching the API using Axios, I am able to successfully log the data in the console. However, when trying to display the data in the child view, I en ...

Reduce the identification number within a JSON array following the removal of an item

Within my local storage, I maintain a dynamic array. Each entry is accompanied by an ID that increments sequentially. If a user opts to delete an entry, it should be removed from the array while ensuring that the IDs remain in ascending order. For example: ...

Create a random word from a single string within the data in Nuxt.js

I am in need of assistance. In my Vue Nuxtjs project, I am fetching random words generated from my backend Laravel application through an API response. I need to generate multiple random words from a single string value in the data obtained from my Axios r ...

Simultaneously activate the 'onClick' and 'onClientClick' events on an ASP button using JavaScript

I have encountered an ASP button while working on existing code that has both onClick and onClientClick events attached to it. My goal is to trigger both events by generating a click event from an external Javascript file. The line of code I am using for ...

utilizing the .on method for dynamically inserted elements

I have a code snippet that triggers an AJAX request to another script and adds new <li> elements every time the "more" button is clicked. The code I am using is as follows: $(function(){ $('.more').on("click",function(){ var ID = $(th ...

Mocha Chai: Dive into an array of elements, discovering only fragments of the desired object

Currently, I am utilizing the assert syntax of chai. I have a dilemma regarding checking an array of objects for a specific object. For example: assert.deepInclude( [ { name: 'foo', id: 1 }, { name: 'bar', id: 2 } ], { n ...

Creating a dynamic dropdown menu that changes based on the selection from another dropdown menu

I'm working on a project that requires users to make specific selections in dropdown menus that are interconnected. Does anyone know how to set up a form so that the options in dropdown menu #2 change based on what the user selects in dropdown menu #1 ...

The NodeJS module 'request' is producing symbols instead of expected HTML content

Currently, I am delving into the world of Nodejs and experimenting with web scraping using node.js. My tools of choice are the node modules request and cheerio. However, when I attempt to request a URL, instead of receiving the HTML body, I get strange s ...

Is there a way to determine the model name programmatically within a Sails.js lifecycle callback?

Two models are present, with one model extending from the other. For all sub-models to inherit a lifecycle callback defined in BaseObject, I need a way to retrieve the name of the model being acted upon within the callback. This information is crucial for ...

Conceal the parent div from its sibling within the same parent container

My goal is to conceal a parent component from its child element. I attempted to achieve this by using the parent component as a background while adding additional backgrounds to the child elements for overriding purposes. However, this method did not work ...

Is there a method to modify the arrangement in which 3 specific HTML elements are displayed (i.e., their hierarchy in relation to one another)?

I have 3 "p" elements and I'm trying to find a way to change the order in which they load on the page using JS or CSS. Below is an example of what I've attempted so far. When you click on the first box labeled "about 1," it opens up and displays ...

Discovering the presence of a NAN value within a JSON string

Consider the following scenario: I have a function that receives jsonData in JSON format, and I want to validate the variable jsonData to check for NaN. How can I achieve this? function save() { var jsonData = getEnteredValue(); $.ajax({ ...

Include web browsing history

In my ASP.Net/VB project, I am facing an issue with floating DIVs. Whenever users try to close the floating DIV by clicking on the back button in their browser, it creates a confusing experience. My solution is to add a "#" entry to the browser history wh ...