find sum of Boolean values JavaScript object array

前端 未结 4 936
天命终不由人
天命终不由人 2020-12-31 07:34

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,
  \"st         


        
相关标签:
4条回答
  • 2020-12-31 07:53
    var result = myObj.reduce((sum, next) => sum && next.status, true);
    

    This should return true, if every value is true.

    0 讨论(0)
  • 2020-12-31 08:00

    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);

    0 讨论(0)
  • 2020-12-31 08:05

    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.

    0 讨论(0)
  • 2020-12-31 08:18

    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);
    
    0 讨论(0)
提交回复
热议问题