Exploring JavaScript - iterating over an array to validate a condition

I am currently working on a customized high charts graph where the color of each bar should dynamically change based on the title of an object. In my array graphData, each object has a title key.

There are 5 potential titles:

"LOW", "MEDIUM-LOW", "MEDIUM", "MEDIUM-HIGH", and "HIGH"

My goal is to iterate through the array and assign a specific color to each bar corresponding to its title.

Currently, all bars in the graph are assigned the same color based on the last title in the array. I want each bar's color to be determined independently.

For instance, if the last title in the array is "MEDIUM-HIGH," the entire graph turns #DD5F0C.

Here is a snippet of my code:

Array:


graphData: [
    { title: "LOW", result: 62582 },
    { title: "MEDIUM-LOW", result: 57758 },
    { title: "LOW", result: 8795 },
    { title: "HIGH", result: 262525 },
    { title: "MEDIUM-HIGH", result: 167168 }
]


let graphColor = ""

for (i = 0; i < graphData.length; i++) {
    if (graphData[i].title === "LOW") {
        graphColor = "#0D6302"
    } else if (graphData[i].title === "MEDIUM-LOW") {
        graphColor = "#0B7070"
    } else if (graphData[i].title === "MEDIUM") {
        graphColor = "#DC9603"
    } else if (graphData[i].title === "MEDIUM-HIGH") {
        graphColor = "#DD5F0C"
    } else if (graphData[i].title === "HIGH") {
        graphColor = "#C50710"
    }

}

HighCharts code :


Highcharts.chart('container', {
    chart: {
        type: 'bar'
    },
    title: {
        text: "Bar Graph"
    },
    xAxis: {

    },
    yAxis: {
        min: 0,
        formatter: function() {
            return this.value + "%";
        },
        title: {
            text: '% of Total'
        }
    },
    legend: {
        reversed: false
    },
    plotOptions: {
        series: {
            stacking: 'normal'
        }
    },
    series: [{
        name: `graphData[0].title`,
        color: graphColor,
        data: [graphData[0]],
    }, {
        name: 'graphData[1].title',
        color: graphColor,
        data: [graphData[1]],
        showInLegend: false,
        linkedTo: ":previous"
    }, {
        name: 'graphData[2].title,
        color: graphData[0].title,
        data: [graphData[2]]
    }, {
        name: graphData[3].title,
        color: '#DC9603',
        data: [graphData[3]]
    }, {
        name: graphData[4].title,
        color: graphColor,
        data: [graphData[4]]
    }, {
        name: graphData[5].title,
        color: graphColor,
        data: [graphData[5]]
    }]
});

The expectation is for the color attribute to dynamically change based on the corresponding graphData.title value at each index.

Answer №1

If you're facing issues, it might be because the number of entries in graphData doesn't align with the single graphColor variable available to store colors. Your code snippets seem incomplete, so I'll assume the surrounding code structure. To simplify things and enhance flexibility, consider building up your series data directly within the for-loop for easy use in the Highcharts.chart function call. This approach not only improves readability but also allows for scalability if more data rows are required.

// Build the series data array here for straightforward usage in chart call
const series = new Array(graphData.length);
for (let i = 0; i < graphData.length; i++) {
  let graphColor = "#000000";  // Default color just in case
  // Can utilize if/else or switch statements here
  if (graphData[i].title === "LOW") {
    graphColor = "#0D6302";
  } else if (graphData[i].title === "MEDIUM-LOW") {
    graphColor = "#0B7070";
  } else if (graphData[i].title === "MEDIUM") {
    graphColor = "#DC9603";
  } else if (graphData[i].title === "MEDIUM-HIGH") {
    graphColor = "#DD5F0C";
  } else if (graphData[i].title === "HIGH") {
    graphColor = "#C50710";
  }

  series[i] = { 
    name: graphData[i].title,
    color: graphColor,
    data: [graphData[i].result]
  };
}

// Adjust the series data as necessary
series[1].showInLegend = false;
series[1].linkedTo = ":previous";

Highcharts.chart("container", {
  chart: { type: "bar" },
  title: { text: "Bar Graph" },
  xAxis: {},
  yAxis: {
    min: 0,
    formatter: function() {
      return this.value + "%";
    },
    title: { text: "% of Total" }
  },
  legend: { reversed: false },
  plotOptions: { series: { stacking: "normal" } },
  series: series
});

Answer №2

I'm not entirely clear on what your goal is, but you might want to consider implementing it in this manner:

const colorMap = { "LOW":"#AABBCC",
"MEDIUM-LOW": "#DDEEFF",
"MEDIUM": "#112233",
"MEDIUM-HIGH": "#445566",
"HIGH":"#778899"
}

... 

series: [{
    name: `graphData[0].title`,
    color: colorMap[graphData[0].title],
    data: [graphData[0]],
  }, {

Answer №3

One method in Highchart involves iterating through the series after initializing the chart to set specific colors for each series individually.

For a demonstration, visit: https://jsfiddle.net/BlackLabel/6hm4ebna/

  chart: {
    type: 'bar',
    events: {
      load() {
        let chart = this;

        chart.series.forEach(s => {
          console.log(s)
          if (s.name === 'test1') {
            s.update({
              color: 'red'
            })
          }
         else  if (s.name === 'test3') {
            s.update({
              color: 'green'
            })
          }
        })
      }
    }
  },

Explore the API here: https://api.highcharts.com/highcharts/chart.events.load

If you require further assistance, try replicating your data on an online editor for easier troubleshooting.

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

What are the steps to calculate the sum and product of values extracted from TextViews within a ListView, and then showcase the results

I am a beginner in programming and I could use some help with this task. I have an Activity that contains a button and a listview. The listview displays values such as name, price, category, and quantity, which are defined through an adapter. I am trying t ...

Tips for showing form values in pop-up boxes based on their unique identifiers

I am experiencing an issue with displaying posted values in a pop-up box. Specifically, when I click on "Book now", it only shows one set of id values for all entries. For example, if I click on the 1st row's "Book now" button, it displays the values ...

Which mobile tab switches should be tuned in to?

Within my React code, I have implemented a function to track the reconnectedCallback when using the following snippet: import { useEffect, useState } from "react"; import usePrevious from "../usePrevious"; const useTabVisible = (reco ...

Angular's implementation of a web socket connection

I am facing an issue with my Angular project where the web socket connection only opens upon page reload, and not when initially accessed. My goal is to have the socket start as soon as a user logs in, and close when they log out. Here is the custom socke ...

Converting a String into an Array using PHP

Imagine this scenario: I receive the following string from an API: parseresponse({"eurusd":{ "id": "eurusd", "category": "Forex", "price": 1.3161, "name": "EUR/USD", "buy": 1.3162, "sell": 1.3159, "change": 0.00, "date":1328288216000}}); Despite my effor ...

Implementing jsGrid: Appending a row with JSON information

Is there a way to dynamically insert a row in jsGrid? I found some helpful code examples at https://github.com/tabalinas/jsgrid/blob/master/demos/db.js ...

Is there a benefit to using middlewares instead of the standard built-in functions in Express.js?

Express.js offers a wide range of middlewares that replace built-in functions. One example is body-parser, which parses HTTP request bodies, replacing the built-in function express.bodyParser. body-parser replaces the built-in function express.bodyParse ...

express.js loop execution timing issue

My current code is not waiting for the loop to finish before printing {"personalchats":[]} I need to send after the for loop has completed. How can I fix this issue? connection.query("SELECT * FROM personalchat WHERE user1ID = ? OR user2ID = ?", [userID, ...

The calculator is experiencing issues with JavaScript functionality

Having some trouble developing a calculator using HTML5, CSS, and JavaScript. After passing my HTML and CSS through validators successfully, I encountered issues when adding JavaScript functions to enable the functionality of the buttons on the calculator. ...

The component 'AddPlaceModal' could not be located in the path '~/components/AddPlaceModal.vue'

Recently, I started incorporating Nuxt for Vue into my projects. In an attempt to enhance my page, I added a new component within the /components folder. However, I encountered a warning during compilation: "export 'AddPlaceModal' was not found ...

Remove all stored data from localStorage and update the view in Backbone framework

Hi, currently I am using backbone localstorage and facing an issue where I need to clear the localstorage every time a user hits the search button. This will allow me to add new data to the localStorage without any conflicts. Additionally, I am attempting ...

Is there a way to detect the presence of a @keyframes rule without having to loop through all the

Looking for a method to determine if a CSS3 animation with a specific name is present, without the need to loop through all CSS rules. Any solution using either a JS library or plain JS will suffice. ...

Having trouble getting basic HTML to function with Vue.js

I am new to vue.js and decided to follow the steps in this tutorial: https://www.sitepoint.com/getting-started-with-vue-js/ After copying the code into my HTML, I encountered some issues. Could someone please assist me in identifying what might be going w ...

The unspoken rules of exporting and importing in TypeScript

In comparison to Java (as well as other programming languages), TypeScript provides multiple options for exporting and importing entities such as classes, functions, etc. For instance, you have the ability to export numerous classes, constants, functions ...

Are your file uploaders malfunctioning by saving empty image files?

I am currently working on a file uploader using JavaScript and Classic ASP. The process involves importing an image into a canvas, converting it to a base64 URL, and then sending that URL to the ASP script for decoding and downloading. Although my AJAX re ...

Menu selection that changes dynamically based on radio button selection

Currently, I have four radio buttons and my goal is to have a drop-down menu change based on the selected radio button. Should I pre-write all the drop-down options and display them accordingly, or would it be better to use ajax to fetch the values from th ...

Utilize a single array to point to multiple elements

I am curious about the potential to create a unique scenario using JavaScript. Imagine having two arrays: a = [1, 2, 3] b = [4, 5, 6] What if we could combine these arrays into a new array, c, that encapsulates both: c = [1, 2, 3, 4, 5, 6] The intrigui ...

At which location within the script should I insert the document.title in order to update the title every xx milliseconds?

I have been working on a script that refreshes certain #id's. Additionally, I would like to update the page title, which involves some flask/jinja2. I've attempted placing document.title = {% block title %} ({{online_num}}) Online Players {% en ...

Add a <div> element to a webpage in a random location every time the page is refreshed

I have a variety of 2 types of <div>s displayed on a single page. Collection 1 consists of: <div class="feature">content 1</div> <div class="feature">content 2</div> ...and so forth. Collection 2 consists of: <div class ...

Obtain the response header variable within a Shiny application

In Apache, the LDAP login is passed to a variable called X-Remote-User in the header: https://i.sstatic.net/7jyxO.jpg I am unsure how to retrieve this information in my Shiny app. Does anyone have any ideas? Maybe using JavaScript could be a solution? ...