What is the most effective way to compare a property with the values stored in an array of objects?

d :

{"children":[{"name":"China","children":[{"name":"China","value":400,"percentage":"33.33"}],"index":0},{"name":"England","children":[{"name":"England","value":300,"percentage":"33.33"}],"index":1},{"name":"Malaysia","children":[{"name":"Malaysia","value":500,"percentage":"25.00"}],"index":2},{"name":"South Korea","children":[{"name":"South Korea","value":600,"percentage":"50.00"}],"index":3}]}

Array of object

cfg.thresholdSetting.thresholds = [{"dType":"threshold","from":0,"to":30,"color":"rgb(217, 20 ,39)"},{"dType":"threshold","from":30,"to":70,"color":"rgb(242, 145, 10)"},{"dType":"threshold","from":70,"to":120,"color":"rgb(33, 145, 49)"}]

Following that, there is a property :

rect.style("fill", function (d, i) {

    for (var k = 0; k < fromValues.length; k++) {
      console.log("percentage : " + d.percentage)
      console.log("from value : " + fromValues[k])
      console.log("to value : " + toValues[k])
         if (d.percentage >= fromValues[k] && d.percentage <= toValues[k]) {
           return cfg.thresholdSetting.thresholds[k].color;
         }
         else {
           return "#808080";
         } 
    }
  })

However, the output for the 'from' and 'to' values remains unchanged. How can I efficiently compare these values given that the outer loop iteration is dependent on the data present?

Current Output

https://i.sstatic.net/T7gYi.png

Expected Output

d.percentage = 33.33
from value   = 0
to value     = 30

d.percentage = 33.33
from value   = 30
to value     = 70

d.percentage = 33.33
from value   = 70
to value     = 120 

d.percentage = 50.00
from value   = 0
to value     = 30

d.percentage = 50.00
from value   = 30
to value     = 70

d.percentage = 50.00
from value   = 70
to value     = 120

Answer №1

From the given scenario, it appears that you are utilizing d3 and aiming to assign colors to rectangles based on the bin they fall into. Assuming that "#808080" serves as the default color when data does not align with any bin:

rect.style("fill", function(d) {
    var color = cfg.thresholdSetting.thresholds.filter(function(t, i) {
        return d.percentage >= t.from && d.percentage < t.to;
    });
    return color.length > 0 ? color[0].color : "#808080";
});

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

How can I make sure an animation only plays once during the current session?

I'm facing a dilemma with my website page that showcases animations using react-anime and react-typing-animation. The issue at hand is how to animate certain elements only once per session. In other words, if the main page animation triggers when the ...

Retrieving selected values from an ngx dropdown list

I am having trouble implementing ngx dropdown list in this way: <ngx-dropdown-list [items]="categoryItems" id="categoriesofdata" [multiSelection]="true" [placeHolder]="'Select categories'"></ngx-dropdown-list> ...

The Material UI list element fails to appear on the screen

I am encountering an issue where I am trying to display a Material UI list within a drop-down menu (using the Material UI drawer component) for mobile view, but the actual list is not appearing as expected. The code snippet for the list is as follows: con ...

Experiencing difficulty retrieving the variable within a NodeJs function

Currently, I am utilizing the NodeJS postgresql client to retrieve data, iterate through it and provide an output. To accomplish this, I have integrated ExpressJS with the postgresql client. This is a snippet of my code var main_data = an array conta ...

Leveraging async/await within a React functional component

Just getting started with React for a new project and facing challenges incorporating async/await functionality into one of my components. I've created an asynchronous function called fetchKey to retrieve an access key from an API served via AWS API ...

Discover the variance between two arrays and display reciprocal alterations using PHP

There are 2 arrays available: $oldValues = array(125 => 'hello', 126 => 'bye', 131 => 'hi', 141 => ''); $newValues = array(125 => 'hello world', 126 => 'bye', 131 => 'h& ...

The React Material Component stubbornly resists being horizontally aligned in the Code Sandbox

Currently, I am working on getting my Material design to function properly within the CodeSandbox environment. One issue I am encountering is attempting to center it horizontally. As of now, it appears like this: https://i.sstatic.net/ZK02y.png To make ...

The oninput() event does not trigger on phones and tablets

Currently, I am in the process of developing an application using PhoneGap. An issue has arisen where my code runs perfectly fine when tested on a browser, but the onInput() function does not seem to trigger on mobile devices. <div class="t1">09< ...

Is there a way to insert a secured page right before accessing the dashboard?

I am trying to create a locked page that will display a message when users access the web app from a mobile device and load a mobile layout page displaying a message like mobile is not supported. I was considering using document.addEventListener('DOMC ...

The issue of req.file being consistently undefined in Node.js multer

I am having issues trying to upload a file using multer because the req.file is always undefined and the destination folder remains empty: Server: var express = require('express'); var multer = require('multer') var app = express(); ...

Unexpected issue with PHP/Ajax/JQuery response functionality

I am experiencing an issue with my index.php file. Here is the code: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="ajax.js"></script ...

Elements in Motion

Working on a parallax effect, I've managed to assign unique scroll speeds to (almost) every element. Moreover, these elements are programmed not to activate their scroll speed until they enter the viewport. Below is the JavaScript code for trigger co ...

How can one overcome CORS policies to retrieve the title of a webpage using JavaScript?

As I work on a plugin for Obsidian that expands shortened urls like bit.ly or t.co to their full-length versions in Markdown, I encounter a problem. I need to fetch the page title in order to properly create a Markdown link [title](web link). Unfortunatel ...

What is the process for converting an <input type="file> into a base64 string?

Currently, I'm attempting to send an image to my express backend by including the image directly in the post request body. var imgValue = document.getElementById("image").value; Within my post request: body : JSON.stringify({ image:imgValue ...

In JavaScript, is it possible to manually trigger a DOM update during consecutive prompts?

My goal is to create a program that transitions between prompts and updates on a page in a cyclical manner. However, when I simplify the issue to just two append calls and two prompts, I notice that the page only visually updates after the second prompt ca ...

What is the best method for creating a top margin that is dependent on the height of the browser?

Is there a way to make the CSS margin: top; on my HTML main_content element relative to the browser window? I want the main_content to always stay at the bottom of the browser window. How can I achieve this? I attempted the following code, but it didn&apo ...

Implementing TypeScript with styled components using the 'as' prop

I am in the process of developing a design system, and I have created a Button component using React and styled-components. To ensure consistency, I want all my Link components to match the style and receive the same props as the Button. I am leveraging t ...

Transform a log file into a JSON structure

In my log file titled request.log, the following entries are present: [2022-06-30T09:56:40.146Z] ### POST https://test.csdf/auth/send_otp { "method": "POST", "headers": { "User-Agent": "testing&q ...

Implementing a return of a view from a Laravel controller function after an AJAX request

I'm currently working on a bookstore project where users can add books to their cart. Users have the option to select multiple books and add them to the cart. When the user clicks on the Add to Cart button, I store the IDs of the selected books in a J ...

Issue with dat.gui not displaying correctly within a WebGL container

When attempting to display my dat.gui interface with a button and textbox on top of my WebGL window, I encounter this issue: https://i.sstatic.net/N9peP.png The section for "Close Controls" in the dat.gui is visible, but strangely the button and textbox ...