CYNTHIA Blessing
CYNTHIA Blessing

Reputation: 71

I can't sum every instance of a property in State

After resolving this question. At the last phase of the project, I am now having an issue with summing the votes for each of the political parties. Someone suggested to me to use Redux, I learnt it and started using the state management system, but unfortunately, I got stuck at the point of adding new state values. I suspect it was from my action that was meant to update the array.

The issue I was originally having is on how to add state values per political party. I want to know the sum of all APC and PDP votes individually. I have tried different techniques but none was successful, this is the last clean [https://github.com/CodingIsFood/e-election-collation-app state of the code].

Please I look forward to stackoverflowers assisting me to resolve the issue (either the redux version or the non-redux version).

Basically, what I need an algorithm for is that let's say we have a property x, which is in a component A, the value of x changes based on the inputs provided by another component B. There is a parent child relationship between A and B. I want to sum every instance of x, every-time it changes.

Upvotes: 0

Views: 124

Answers (1)

chriss
chriss

Reputation: 669

based on structure of your datasource file, following function executed on your data should work

Datasource.reduce((sum, a) => {
    if(!sum.apcVotes) sum.apcVotes = 0;
    if(!sum.pdpVotes) sum.pdpVotes = 0;
    sum.pdpVotes += parseInt(a.pdpVotes)
    sum.apcVotes += parseInt(a.apcVotes)
    return sum;
}, {})

Result will be in following structure:

{apcVotes: 250, pdpVotes: 301}

Upvotes: 1

Related Questions