18

Hi i am trying to find the sum of Boolean values in the object array in JavaScript

My json like be

var myoBj = [{
  "id": 1,
  "day": 1,
  "status": true
}, {
  "id": 2,
  "day": 1,
  "status": false
}, {
  "id": 3,
  "day": 1,
  "status": false
}, {
  "id": 4,
  "day": 3,
  "status": false
}];

i want the sum of all status values using reduce function in JavaScript/ typescript

i want to show overall status as true only when all status are true else it should be false

3
  • 2
    Sum of boolean, what you mean ? Commented Jan 19, 2017 at 10:43
  • @PranavCBalan i want to show overall status as true only when all status are true else it should be false Commented Jan 19, 2017 at 11:58
  • 4
    Why .reduce()..? There is an array functor especially tailored for this job called .every(). Commented Jan 19, 2017 at 12:32

4 Answers 4

35
var result = myObj.reduce((sum, next) => sum && next.status, true);

This should return true, if every value is true.

Sign up to request clarification or add additional context in comments.

2 Comments

This solution seems to be neat and simple , Thanks Balint
@SathyaV Maybe neat and simple, but can't beat myObj.every(item => item.status)
12

If you want to sum lets say, day items value depending on the status flag, this can looks like:

var result = myObj.reduce((res, item) => item.status ? res + item.day : res, 0);

Update 1

For overall status in case of all statuses are true you should use every method:

var result = myObj.every(item => item.status);

2 Comments

i want to show overall status as true only when all status are true else it should be false
Thanks TSV for the solution
1

If you must use reduce you can take advantage of the fact that x*false == 0, and so you can do the following:

const myObj=[{id:1,day:1,status:true},{id:2,day:1,status:false},{id:3,day:1,status:false},{id:4,day:3,status:false}],

res = !!myObj.reduce((bool, {status}) => bool*status, true);
console.log(res);

1 Comment

That's crazy, I didn't know multiplying booleans returned 0, 1
1

You could use Array.some with predicate a => !a.status or Array.every with predicate a => a.status.

Either of them will short-circuit if you find a mismatch, while Array.reduce will not.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.