/    Sign up×
Community /Pin to ProfileBookmark

Help with reduce

I have an array and inside a bunch of records which are objects.
Each record object has a key “published” with a value of 0 or 1 and I am simply trying to get a count of all the ones published so if 5 are published I want to return a value of 5.

I have this:

“`
const total = this.records
.map(function(b) {
return b.published
})
.reduce(function(p, c) {
return p + c
})
“`

But it still says 7 ( there are 7 records in total for the sake of the question, 3 published, 4 not)
When I need to get 4 as total published.
Can anyone assist me in this issue.

What am I doing wrong?

Thanks,

Dave

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@daveyerwinAug 29.2019 — ``<i>
</i>&lt;script&gt;
var records=[{published:1},{published:0},{published:1},{published:1},{published:0},{published:0},{published:1}];
records.forEach(function(a){
if(!records.totalPublished)records.totalPublished=0;
records.totalPublished += a.published
})
alert(records.totalPublished);//alerts 4
&lt;/script&gt;<i>
</i>
``
×

Success!

Help @movepixels 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 5.18,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

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