/    Sign up×
Community /Pin to ProfileBookmark

Sum data (column b) based on data other data (column a)

Hello,

I couldn’t find a solution to this:

I have an array with 3 columns:
column 1 = month
column 2 = number of female visitors
column 3 = number of male visitors

The number of rows depends on the number of months; if there are any visitors in that month and some months could have more than 1 occurrence.

For each month I need to calculate the total of female and total of male visitors; output must be something like this:

Totals month 1:
total female visitors = 15
total male visitors = 38

Totals month 2:
total female visitors = 28
total male visitors = 11

X no visitors at all in March
X visitors at all in April

Totals month 5:
total female visitors = 15
total male visitors = 38

I’ve managed to calculate the totals per entire column 1 and column 2, but can’t get the montly totals per column; could anyone advise pls? Thanks already for the tips.

[code]
var visitorsPerMonth = [
[1, 24, 15],
[1, 30, 22],
[3, 28, 41],
[5, 31, 58],
[5, 31, 58],
[5, 11, 58],
[7, 21, 38],
];

var totalColumn1 = 0;
var totalColumn2 = 0;
for(var i = 0; i < visitorsPerMonth.length; i++){
totalColumn1 = totalColumn1 + visitorsPerMonth[i][1];
totalColumn2 = totalColumn2 + visitorsPerMonth[i][2];
};

console.log(totalColumn1, totalColumn2);
total column 1 = 176
total column 2 = 290
[/code]

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumSep 16.2021 — Check if this javascript does the job:
``<i>
</i> const visitorsPerMonth = [
[1, 24, 15],
[1, 30, 22],
[3, 28, 41],
[5, 31, 58],
[5, 31, 58],
[5, 11, 58],
[7, 21, 38],
];

let nrVisitsFemale = [];
let nrVisitsMale = [];
visitorsPerMonth.forEach(item =&gt; {
if (!nrVisitsFemale[item[0]]) {
nrVisitsFemale[item[0]] = item[1];
} else {
nrVisitsFemale[item[0]] += item[1];
}
if (!nrVisitsMale[item[0]]) {
nrVisitsMale[item[0]] = item[2];
} else {
nrVisitsMale[item[0]] += item[2];
}
});
console.log(nrVisitsFemale);
console.log(nrVisitsMale);<i>
</i>
``
Copy linkTweet thisAlerts:
@polygonStormauthorSep 16.2021 — hello Sempervivum,

100%, thank you! ;-)
×

Success!

Help @polygonStorm spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...