How can I print only the final count onto the console?
I have a csv file with name and ages of people. I want to get the count of people under 30.
I have tried the below code.
<script src='https://d3js.org/d3.v7.min.js'></script>
<script>
let thiscsv = 'my csv link here';
let count=0;
d3.csv(thiscsv, function(data) {
if(data.age>30)
{
count++
}
console.log(count);
});
</script>
It checks each line and prints in it the console each time adding 1 count wherever it is true until the end of the csv file. I want to print only the final count directly onto the console. How can I do this?
Solution 1:
Please read the answer you received for your previous question carefully (and I suggest you upvote it, as I did): the first thing the answerer says is that you need then()
. This is D3 v7, it doesn't use a callback like D3 v4 or less. The way you're doing now the so called row function will run for each parsed row, as expected.
This is what you should do, again, pay attention to the then()
:
<script src='https://d3js.org/d3.v7.min.js'></script>
<script>
let thisCsv = URL.createObjectURL(new Blob([`name,age
foo,12
bar,34
baz,63
foobar,17,
barbar,43,
barbaz,39`]));
let count = 0;
d3.csv(thisCsv, d3.autoType).then(data => {
data.forEach(d => {
if (d.age > 30) count++
});
console.log(count);
});
</script>
Also, notice the d3.autoType
: without that, your CSV numbers will be strings, not numbers.
Solution 2:
If you JUST want to count ppl with ages above 30:
const process = data => {
const ages = data.map(({Age}) => +Age) // make sure it is a number
.filter(num => num > 30)
.length
console.log("Total ppl with age above 30:",ages)
}
// uncomment when you want to read a file
// let mycsv = 'example.csv';
// d3.csv(mycsv)
//.then(function(data) {
process(data)
//})
<script src='https://d3js.org/d3.v7.min.js'></script>
<script>
const data = d3.csvParse(`PassengerId,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked
111,1,"Ken, Mr. James",male,34.5,0,0,330911,7.8292,,A
112,2,"Will, Mrs. James",female,47,1,0,363272,7,,B`);
</script>