The if-else statement is providing a misleading outcome

While working on my map using leaflet, I decided to implement a dynamic color concept based on input data. However, despite comparing 3 sets of data to ensure accuracy, some parts of the color scheme are displaying incorrect results. Below is the snippet of the JavaScript code responsible for the color logic:

data_increase = [5]
data_decrease = [14]
data_equal = [29]
//data derived from input

function color_region_a(fillColor) {
  if (data_increase < data_decrease && data_decrease > data_equal)
    return 'green';
  else if (data_increase < data_decrease && data_decrease < data_equal)
    return '#7FFF00'; //color between green and yellow (Chartreuse)
  else if (data_equal > data_increase && data_equal > data_decrease)
    return 'yellow';
  else if (data_equal > data_increase && data_increase > data_decrease)
    return 'orange';
  else(data_increase > data_decrease && data_increase > data_equal)
  return 'red';
};

Although there seems to be no issue with the map implementation as seen below:

var region_a = L.geoJson(RegionA, {
        "color":"white",
        fillColor: color_region_a(),
        opacity: 10,
    }).addTo(map)

The problem lies in the fact that the function color_region_a always returns red for the fillColor instead of the expected result #7FFF00 or chartreuse. Can anyone pinpoint where I might have gone wrong in my approach? Any alternative methods would be appreciated. Thank you.

Answer №1

These are both array variables, so you cannot directly compare them in their current state.

In order to compare them, you have two options: either convert them into raw numbers (not in an array) or use the following method:

data_increase[0] < data_decrease[0]

Answer №2

You have made 2 errors.

  1. The comparison [5] > [29] is incorrect. It should be 5 > 29. Use
    data_increase[0] < data_decrease[0]
    instead.
  2. You neglected to include an 'if' statement in the last 'else' block.

Check out the demonstration below.

data_increase = [5]
data_decrease = [14]
data_equal = [10]
//data is based on input

function color_region_a(fillColor) {
  if (data_increase[0] < data_decrease[0] && data_decrease[0] > data_equal[0])
    return 'green';
  else if (data_increase[0] < data_decrease[0] && data_decrease < data_equal[0])
    return '#7FFF00'; //color between green and yellow (Chartreuse)
  else if (data_equal[0] > data_increase[0] && data_equal[0] > data_decrease[0])
    return 'yellow';
  else if (data_equal[0] > data_increase[0] && data_increase[0] > data_decrease[0])
    return 'orange';
  else if(data_increase[0] > data_decrease[0] && data_increase[0] > data_equal[0])
  return 'red';
};

console.log(color_region_a());

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

Why is the jQuery ajax file uploading feature failing to function properly in the IE9 standard mode?

My file upload function works well in browsers like Chrome and IE10, but encountered an issue when tested on IE9. The Action controller reported that Request.Files were returning files with '0' length. I'm unsure if this problem is related ...

Issue arising during reconnection following a disconnection in the node-redis client

I'm struggling to understand why the SocketClosedUnexpectedlyError error is being triggered in the code snippet below: const redisClient = require('redis').createClient(); redisClient.connect().then(function() { return redisClient.disconn ...

Is it possible to display one division on top of another with a transparent opacity effect in HTML?

I'm struggling with designing web pages and currently working on a page on codepen.io using code from this link. <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1 ...

`Why am I having difficulty transmitting HTML content with Node.js through Mailgun?`

I've been facing issues with sending HTML in my emails. To troubleshoot and prevent errors, I've opted to utilize Mailgun's email templates. Although I can successfully send out the emails, the problem arises when I receive them - the HTML ...

Verifying a user's name when navigating a route

Hey everyone, I've been working on this project for the past 3 hours and could really use some help. I created an express webapp with an admin page. The register and login functionalities are all set up using passport. I have a function to check if th ...

Can Javascript work together with HTML?

Can 'this' be utilized in this specific scenario? var td = document.getElementsByTagName("td"); for (var i = 0; i<td.length; i++){ td[i].id = 'abc' + i; }; for (var i = 0; i<td.length; i++){ td[i].onclick = c ...

Incorporating HTML into the Ajax Response

I recently encountered a strange issue with a service that returns an HTML page as the AJAX response. This page contains a form that is automatically triggered by scripts within the page, resulting in a POST request being sent when the page is rendered. My ...

AngularJS does not recognize a dynamically created array when using ng-include with ng-repeat

Issue with ng-repeat Directive I have encountered a problem where the ng-repeat directive does not track the addition of a new array, specifically 'options'. This issue arises when the directive is used within a template displayed using ng-dialo ...

What is the process for activating an event before another event on the same element with vanilla JavaScript?

Having an issue with the eventListener function. I am using the external library jquery.jstree-pre1.0fix2, which triggers a blur event on an input in my case. However, I need to trigger my event before the one from the library. I have come across some sol ...

Encountered an Unhandled Runtime Error in NextJs: Invalid Element Type

Attempting to build an Instagram clone following a YouTube tutorial from a year ago has led to various errors arising from nextjs14. I have managed to resolve all of them except for one particular issue: Error: Element type is invalid - expected a string ...

Is it possible to refresh text in table without clearing icons?

Is there a way to maintain icons in table rows when editing text fields from a dialog? Currently, regardless of whether I use .html() or .text(), the icons disappear. I suspect that utilizing .content() may be a solution, but I'm unsure how to impleme ...

retrieve fresh information from the API

Hello! I am attempting to retrieve new data from an API by filtering it with a JSON file. My goal is to filter the data from the API using the JSON file and extract any new information. const jsnf = JSON.stringify(fs.readFileSync("./data.json" ...

Activate audio when the link is clicked

Recently, I created a compact web application and it's almost complete. However, there is one cool functionality that I am missing. My goal is to have a sound play when the user clicks a link, but after playing, I want the navigation to continue as us ...

Incorporating a JavaScript code into my SharePoint master page to automatically deselect a checkbox resulted in updating the page title

I've integrated the following JavaScript code into my SharePoint master page: <script type="text/javascript> function DefaultUploadOverwriteOff() { if (document.title== "Upload a document") { var input=document.querySelectorAll("input"); ...

Ways to prevent the "Site not secure" warning on an Express server with HTTPS configuration

In the process of creating an Express app, I decided to enable HTTPS for a secure connection. After obtaining a certificate from StartSSL.com and importing it into my server successfully, everything seemed set up correctly. However, an issue has arisen: h ...

When altering a single scope variable in AngularJS, the effect cascades to impact other scope variables as well

After uploading my code on fiddle, I noticed that changes made to the myAppObjects variable also affect another variable. Here is the link to the code: https://jsfiddle.net/owze1rcj/ Here is the HTML part of the code: <div ng-controller="MyCtrl"&g ...

Activating Dynamic Functionality through JavaScript Input

I am currently working on a form in Apex 4.1 where I have an address lookup field that utilizes JavaScript to connect to an address database and populate separate fields with the address details (address1, address2, town, postcode). On the same page, I ha ...

Utilizing Kendo MVVM to Bind to an Self-Executing Anonymous Module Function

Currently, I am experimenting with the Kendo UI MVVM framework and attempting to bind it to a self-executing anonymous modular function. The situation is a bit complex, as the functionality is only somewhat working. Although the module is being updated whe ...

What steps can be taken to resolve the issue of the <td> element not being allowed as a child of an <a> tag?

https://i.stack.imgur.com/nsdA7.png How can I address these warnings? I utilized the material UI table component and suspect that the warnings are originating from component={Link} to={/patient/${patient.id}} <TableContainer className={styles.tableCo ...

Determine the necessary adjustment to center the div on the screen and resize it accordingly

Currently, I am in a situation where I must develop a piece of code that will smoothly enlarge a div from nothing to its final dimensions while simultaneously moving it down from the top of the screen. Each time this action is triggered, the final size of ...