find sum of Boolean values JavaScript object array

会有一股神秘感。 提交于 2019-12-30 04:31:08

问题


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


回答1:


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

This should return true, if every value is true.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/41739710/find-sum-of-boolean-values-javascript-object-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!