Working with arrays of objects in D3.js using Javascript

Seeking guidance as I navigate through the world of javascript and D3.js.

I have two distinct data sets (arrays of objects) that I hope to merge. My goal is to align the National Average Scores with the State Average Scores by matching the 'Answer' field. To explore the data, feel free to copy and paste this into Tributary.

// National Averages Data Set
var nationaldataset = [];
var nAvg = "http://data.medicare.gov/resource/89u8-shx4.csv"; 
var nscore = "HCAHPS Answer Percent";
var nquestion = "HCAHPS Question";
var nanswer = "HCAHPS Answer Description";

d3.csv( nAvg, function(data)  {
    nationaldataset = data.map(function(d) { return [ d[nquestion], d[nanswer], d[nscore] ]; });
    d3.select("body").selectAll("p")
        .data(nationaldataset)
        .enter()
        .append("p")
        .text( function(d) {return d ;} );  

});
// State Averages Data Set
var statedataset = [];
var sAvg = "http://data.medicare.gov/resource/fhk8-g4vc.csv"; //State Average
var sq1 = "Percent of patients who reported that their nurses \"Sometimes\" or \"Never\" communicated well."
var sq2 = "Percent of patients who reported that their nurses \"Usually\" communicated well."
var sq3 = "Percent of patients who reported that their nurses \"Always\" communicated well."
// .. this list continues for 30 columns
d3.csv( sAvg, function(data) {
    sstatedataset = data.map(function(d) { return [ d["State"], d[sq1], d[sq2], d[sq3] ]; });
    d3.select("body").selectAll("p")
        .data(statedataset)
        .enter()
        .append("p")
        .text(function(d) {return d ;} );

});

Despite researching various javascript array methods like Join(), Concatenate(), I still find myself stuck. How can I achieve a task similar to this -

Select nationaldataset.nquestion
, nationaldataset.nanswer
, nationaldataset.nscore
, statedataset.Score
From nationaldataset, statedataset 
WHERE nationaldatset.nanswer = statedataset.columnname 
AND statedataset.State in ['SD', 'MN', 'IA'] 

Answer №1

Regrettably, JavaScript does not have a built-in join operator like some other languages. Instead, you must explicitly search for matches. In the given scenario, a nested loop can be used to achieve this. An example of the code is shown below.

var results = [];
for(var i = 0; i < statedataset.length; i++) {
  if(statedataset[i].State == "SD" ||
     statedataset[i].State == "MN" ||
     statedataset[i].State == "IA") {
    var j = 0;
    for(j = 0; j < nationaldataset.length; j++) {
      if(nationaldataset[j].nanswer == statedataset[i].columnname) {
        break;
      }
    }
    if(j < nationaldataset.length) {
      results.push({
        "nquestion": nationaldataset[j].nquestion,
        "nanswer": nationaldataset[j].nanswer,
        "nscore": nationaldataset[j].nscore,
        "Score": statedataset[i].Score
      });
    }
  }
}

This code snippet generates a data structure that can be utilized with D3. It is worth noting that there may be alternative approaches to achieve the desired outcome in a more elegant manner.

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

Building a dynamic attribute management system with vue and vuetify

In the backend business object, there is a custom attributes data structure that allows clients to add key/value pairs for storing in the database. For instance: Map<String, String> customAttributes; Here's an example of how it would look in th ...

The value of a Highcharts series does not match that of a Data Source

Encountering an issue with Highcharts where the value of this.y does not reflect the data source. The discrepancy is apparent in the image below. Uncertain if this is a bug or user error. Screenshot illustrating the problem You can view my Demo here: htt ...

When working with Nuxt 3, the referrer header may sometimes return as undefined

I am looking to capture the referrer header and store it in a cookie so that I can later use it to populate an axios request during the user's journey on my website. In my app.vue, I currently have the following code snippet: const headers = useReque ...

Addressing the issue of pm2 with netmask 1.0.6 posing a serious security risk

While working on my project, I encountered a problem in the terminal when using the pm2-runtime command for the runtime environment. When running the command npm i, I received warnings at two levels: High netmask npm package vulnerable to octa ...

Tips on displaying a particular JSON attribute?

After starting with a JSON string, attempting to convert it into a JSON object and then trying to print a specific field (such as firstName), I am getting undefined. What could be the issue here? Thank you for your help! var string = '{"firstName ...

Configuring a devServer proxy leads to a 404 error

Within my src/vue.config.js file, I have the following configuration: module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:8081', changeOrigin: true, }, }, }, }; When I c ...

Navigate between pictures using hover in jQuery

I am working on creating a feature where images cycle through individually every 2 seconds, but switch to the right image when its associated link is hovered. So far, I have managed to make the images show up on hover, but I am struggling with getting them ...

Add a fresh listing arranged alphabetically using either JavaScript or jQuery

I currently have a set of lists that are already alphabetically sorted. For example: <ul> <li><a href='#'>Apple</a></li> <li><a href='#'>Banana</a></li> <li><a href=& ...

What is the correct way to utilize the WhatsApp API for sending messages?

Trying to incorporate WhatsApp API notifications into my app has been a challenge. Despite extensive research, I have yet to find an official solution. The existence of the WhatsApp API Business is known, but it currently remains in beta and caters to com ...

Reducing file size through compression (gzip) on express js version 4.4.1

My express js app is functioning as a web server, but I am having trouble with serving unzipped static content (js and css files). I have tried using compression from https://github.com/expressjs/compression, but it doesn't seem to be working for me. ...

What's the reason for text-alignment not functioning properly?

After some testing, I have come up with the following code: .Greetings { width:100%; display:block; text-align:center; font-family: "Times New Roman", Times, serif; font-size:75px; color:#208CB7; } The objective was to center the text on the ...

Implementing a filter in React with data fetched from MongoDB

Hey there! I'm encountering an issue while using the code in Project.jsx and ProductList.jsx. Every time I run the code, it gives me this error message: Warning: Each child in a list should have a unique "key" prop. Check the render method of Product ...

Ways to conceal a primary page section upon clicking a different tab

I am currently implementing the w3schools HOW TO - tabs feature on my website to create tabbed navigation. However, I'm running into an issue where clicking on tabs other than 'Home' still displays the 'Home' content along with the ...

Guide for making an accordion with a close button that is specific to multiple dynamic IDs

I am looking to create an accordion feature. The idea is that when the user clicks on "Show," the text "Show" should be hidden, and the content along with a "Close" button should be displayed. Then, when the user clicks on "Close," the content and "Close" ...

Error message: The "spawn" function is not defined and is causing a TypeError to be thrown in

Having a bit of trouble here. I'm trying to make an async request using redux-thunk in my action creator, and the code looks like this: export const downloadFromYoutube = (download) => { console.log("Hello"); return dispatch => { va ...

Render variable values with Mustache syntax

There are two separate html pages named home and about. Each page contains a js variable defined at the top of the page: var pageAlias = 'home'; // on the home page var pageAlias = 'about'; // on the about page The goal is to pass thi ...

Utilizing an EJS variable within a React render function with webpack - A Guide

I am looking for a way to display personalized information stored in a MySQL database to my users. I am using ejs, webpack, and React for my project. While I found some guidance on how to achieve this without webpack, it doesn't quite fit my needs. Th ...

Implementing dynamic props in Vue2 component by passing arbitrary named variables

Having recently delved into Vue, I am facing a challenge that has left me scratching my head after consulting the documentation: I am struggling to pass an arbitrarily named variable as a prop to a component instance. As per my understanding, props serve ...

Which five key JavaScript concepts should I grasp in order to excel as an AngularJS developer?

Coming from a background of server-side coding, I am delving into the world of AngularJS now. This means I need to have a solid grasp of JavaScript before diving in. If I don't have enough time to master JavaScript completely at the moment, what are ...

Encountering issues with link functionality on homepage due to React-Router v6 and Material-UI Tab integration

I'm currently working on a homepage that requires different page links. Below you can find the necessary code snippet for setting up the tabs and routes for each page: <li> The tabs are located here - <Link to="/demo">D ...