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?