I have a csv file with data like this
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
and so on
I want to count how many of these names in the csv file include Mr and Mrs and other
and using column 'sex' I want to print the number of male and female passengers.
I have tried this but it just prints every line with 0 for Mrs and 1 for Mr instead of giving me the count for Names with Mr
<script src='https://d3js.org/d3.v7.min.js'></script>
<script>
let mycsv = ' some file name';
d3.csv(mycsv, function(data) {
let count = 0;
var theWord = "Mr";
if (data.Name.includes(theWord))
{
count ;
}
console.log(count);
});
</script>
CodePudding user response:
You need to loop.
That can be done with a reduce:
const counts = data.reduce((acc, { Name, Sex }) => {
acc.mr = Name.toLowerCase().includes("mr.");
acc.mrs = Name.toLowerCase().includes("mrs.");
acc.male = Sex.toLowerCase() === "male";
acc.female = Sex.toLowerCase() === "female";
return acc;
}, { mr: 0, mrs: 0, male: 0, female: 0 });
console.log(counts);
<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>
CodePudding user response:
Aren´t we missing any loop in here? Seems like you are just doing 1 iteration and checking 1st object from the *.csv file.
Also just a note - try to stick to let/const, don´t mix var and let declarations, that is not a good practice
CodePudding user response:
The code if (data.Name.includes(theWord)) only runs once and it will return true for any number of "Mr" aslong as it is not zero.
What you need is to loop through the data and count where you condition is true.
But this looks really homework-like, so... sorry, but I will only give these tips and no actual code. (And double sorry if this is not homework.)
