Trouble with incrementing JavaScript dictionary values within a nested for loop

I am currently working on analyzing shark attack data with d3.js using a csv file named shark.csv. I have encountered a problem while implementing a nested for-loop in my code. The csv file contains information about shark attacks categorized by continent and year. My goal is to track the frequency of each continent appearing in each year. Here is a snapshot of the shark.csv file:

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

and this is the desired outcome that I am aiming for: https://i.sstatic.net/vfW9r.png

(please note that the numbers shown are just examples)

To achieve this, I am storing the occurrence count of each continent name for a specific year in a dictionary object, and updating it as follows:

var allYears = [];

var allConti = [];

var allOccurrences = {};

d3.csv("https://raw.githubusercontent.com/eliasdon/proj/main/shark.csv").then(function(data) {

    // get all unique years
    for (var i = 0; i < data.length; ++i) {
        if (!allYears.includes(data[i].Date)) {
            allYears.push(data[i].Date);
        }
    }

    // get all unique continents
    for (var i = 0; i < data.length; ++i) {
        if (!allConti.includes(data[i].Continent)) {
            allConti.push(data[i].Continent);
        }
    }

    for (var i = 0; i < data.length; ++i) {

        for (var j = 0; j < allYears.length; ++j) {

            for (var k = 0; k < allConti.length; ++k) {

                // check if key for matching year and continent exists in dictionary
                if (!(allYears[j] + " " + allConti[k] in allOccurrences)) {

                    // if not, store it with an initial value of 1
                    allOccurrences[allYears[j] + " " + allConti[k]] = 1;
                } else {

                    // if already exists, increment the value
                    allOccurrences[allYears[j] + " " + allConti[k]]++;
                }
            }
        }
    }
    console.log(allOccurrences);
});

This code performs the following steps:

1- Read the csv file

2- Store all unique years

3- Store all unique continents

4- If there is no entry for the combination of

allYears[j] + " " + allConti[k]
(year and continent), create one with a value of 1.

5- If the entry already exists, increase its value by 1

The issue I am facing is that all the keys representing year and continent pairs end up with values equal to the total number of rows in the csv file.

https://i.sstatic.net/3lg9b.png

I am wondering what might be wrong with my implementation of the for-loop?

Answer №1

Ensure to only increment the values in the dictionary that correspond to the current data iteration within the 3rd outer for-loop

var i = 0; i < data.length; ++i
.

Additionally, note that using a = ++a is redundant. It is recommended to either use a = a + 1 or a++/++a. The most commonly preferred style is a++ for incrementing a variable.

Some more suggestions to consider:

  • Prefer using let over var
  • Opt for i++ instead of ++i
  • Use ' instead of "; better yet, utilize template strings ${a} ${b} instead of string concatenation like a + ' ' + b
  • Assign a local variable for the key rather than computing it multiple times
  • Consider using [].forEach instead of traditional for-loops
  • Use if (a[key]) instead of if (key in a)
let allYears = [];
let allConti = [];
let allOccur = {};

d3.csv("https://raw.githubusercontent.com/eliasdon/proj/main/shark.csv").then(data => {
    allYears = [...new Set(data.map(d => d.Date))];
    allConti = [...new Set(data.map(d => d.Continent))];

    data.forEach(d => {
        let key = `${d.Date} ${d.Continent}`
        allOccur[key] = allOccur[key] || 0;
        allOccur[key]++;
    });

    console.log(allOccur);
});

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

ASP.NET Dynamic Slideshow with Horizontal Reel Scrolling for Stunning

I'm curious if there is anyone who can guide me on creating a fascinating horizontal reel scroll slideshow using asp.net, similar to the one showcased in this mesmerizing link! Check out this Live Demo for a captivating horizontal slide show designed ...

Exploring the versatility of orderBy and filter in handling cross-referenced content across multiple JSON objects

Is there a way to filter and search for the item name when the item details are sourced from another JSON object? Demo: http://codepen.io/anon/pen/GjAxKX While the rest of the filtering and ordering functionalities are functioning correctly, I am struggl ...

Utilize JavaScript's $.post function to export PHP $_POST data directly into a file

After spending hours trying to figure this out, I've come to the realization that I am a complete beginner with little to no knowledge of what I'm doing... The issue I'm facing is related to some JavaScript code being triggered by a button ...

Displaying a custom error page in Next.js with the appropriate status code

I recently implemented a custom error page following the instructions provided in the documentation. My goal was to use this error page for specific errors that may occur during the getStaticProps function. Here's how I structured it: const Page: Next ...

Is there a simple method to submit to a URL without relying on ajax?

When it comes to using jQuery, the $.ajax() function is typically used for POST requests to a URL. However, in my particular situation, I am unable to use this function. I need the client to send a POST request to a URL and have the server redirect the use ...

What steps should I take to have a button initiate an AJAX request?

One of the tasks on my list involves a textbox and a button for interaction. Once text is entered into the textbox, I intend to trigger an AJAX request by clicking the button. The purpose of this AJAX call is to extract the text input and incorporate it i ...

verifying an email address through firebase using the verifyPasswordResetCode method

Currently in the process of setting up firebase authentication. Instead of relying on firebase's default pages for recovery password and email verification, I want to handle these processes directly on my website. To customize the recovery steps: U ...

Error encountered while attempting to use single quotation marks in MySQL databases

var comma = ","; var querys = "insert into movie values (" + "'" + movid + "'" +comma + "'" + name + "'" + comma + "'" + genere + "'" + comma + "&ap ...

React Express Error: Unable to access property 'then' of undefined

I'm facing an issue while trying to server-side render my react app for users who have disabled JavaScript and also for better search engine optimization. However, I am encountering the following error: TypeError: Cannot read property 'then' ...

What is the reason for the error that is being caused by using arrow functions in my code

I'm currently working on a React application, but I keep running into errors that are causing issues. Here is the code snippet in question: import React from 'react'; import { Link } from 'react-router-dom'; const LINKS = [ { to ...

Vue composable yields a string value

I am currently using a Vue composable method that looks like this: import { ref } from 'vue'; const useCalculator = (num1: number, num2: number, operation: string) => { const result = ref(0); switch (operation) { case 'add& ...

Ways to reposition JavaScript output within a webpage

I am new to HTML, CSS, and JavaScript and I have a question regarding how they work together. I can use JavaScript to display objects on the page, but I'm unsure how to move them around like other elements. Is CSS the solution for this? Any advice w ...

Exploring ways to display dynamic content within AngularJs Tabs

I need help figuring out how to display unique data dynamically for each tab within a table with tabs. Can anyone assist me with this? https://i.stack.imgur.com/63H3L.png Below is the code snippet for the tabs: <md-tab ng-repe ...

Using gmaps4rails: A guide on extracting JSON data from the controller

I have a model named shop and I want to create a simple alert box using JavaScript that shows the name of the shop when a marker on the map is clicked. Here's my code: # controller @json = Shop.all.to_gmaps4rails do |shop, marker| marker.json({ id ...

Developing a fresh Outlook email using a combination of javascript and vbscript

I have created a custom HTML page with fields and a button to fill out in order to generate a new Outlook mail item. To format the body of the email using HTML, I am utilizing VBScript to create the new mail item. <script> function generateEmail() { ...

Polymerfire: Unable to locate a default bucket

Having an issue with uploading data to the storage Bucket of my app. The line var uploadRef = firebase.storage().ref(); is triggering this error message: Firebase Storage: No default bucket found. Ensure the 'storageBucket' property is set when ...

Including additional data to a page after each iteration in order to display the current progress

I am currently working on a loop that iterates through the lines of a text area and processes each line sequentially. However, I am facing an issue where the page becomes unresponsive until all the data has been processed. Is there a way to dynamically u ...

Refreshing the page using location.reload triggers a reload of various elements

I am currently working on a website that supports multiple languages and utilizes a cookie named nav_lang to determine the user's preferred language for navigation. Whenever a user selects a new language, the cookie is updated accordingly and the page ...

The chat message section is failing to update due to AJAX not refreshing

I recently launched a new website and am facing challenges with the chat feature. Despite using ajax to update the chat messages without refreshing the page, the other user still needs to refresh in order to see the latest message. We are both in the sam ...

Module for Npm that includes unique code for both proxy support and non-proxy support configurations

Is there a way to develop a javascript library (available as a module on npm) with multiple implementations based on the level of proxy support in the environment where it is executed (transpiled to)? From my understanding, babel may not easily transpile ...