Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find sum of Boolean values JavaScript object array

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

like image 806
Sathya V Avatar asked Jan 19 '17 10:01

Sathya V


People also ask

How do you find the sum of an array of objects?

To sum a property in an array of objects:Call the reduce() method to iterate over the array. On each iteration increment the sum with the specific value. The result will contain the sum of the values for the specific property.

How do you count the number of true values in an array?

To count the true values in an array:Check if each value is equal to true and return the result. Access the length property on the array to get the count of the true values.

How do you count true and false in an array?

Use count_nonzero() to count True elements in NumPy array In Python, False is equivalent to 0 , whereas True is equivalent to 1 i.e. a non-zero value. Numpy module provides a function count_nonzero(arr, axis=None), which returns the count of non zero values in a given numpy array.

What is the boolean value of object in Javascript?

The Boolean object represents a truth value: true or false .


2 Answers

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

This should return true, if every value is true.

like image 80
Bálint Avatar answered Oct 13 '22 19:10

Bálint


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);
like image 31
TSV Avatar answered Oct 13 '22 19:10

TSV