Question

What is the sum of true values in an array?

Answer and Explanation

When we talk about the sum of "true" values in an array, we're generally referring to counting the number of elements in the array that are considered "truthy." In the context of programming, and particularly JavaScript, a "truthy" value is one that evaluates to true when coerced into a boolean.

Here's a breakdown of how to achieve this and what it means:

Understanding Truthy and Falsy Values

In JavaScript, certain values are considered "falsy" when evaluated in a boolean context, while others are "truthy". Falsy values are: false, 0, "" (empty string), null, undefined, and NaN. All other values are considered "truthy." This includes objects, arrays, non-zero numbers, and non-empty strings.

Calculating the Sum of True Values

To count the number of truthy values in an array, you can use methods like filter() or reduce() with a boolean check, or you can loop through the array and increment a counter for each truthy value.

Example using `filter()` and `length`

This method filters the array, keeping only the truthy values, and then returns the length of the resulting array.

const arr = [true, false, 1, 0, "hello", "", null, {}, []];
const sumOfTrueValues = arr.filter(Boolean).length;
console.log(sumOfTrueValues); // Output: 6

Example using `reduce()`

This method iterates through the array and uses a counter, incrementing it when the value is truthy.

const arr = [true, false, 1, 0, "hello", "", null, {}, []];
const sumOfTrueValues = arr.reduce((count, value) => value ? count + 1 : count, 0);
console.log(sumOfTrueValues); // Output: 6

Explanation

In both the examples above, the array [true, false, 1, 0, "hello", "", null, {}, []] contains:

  • true: truthy
  • false: falsy
  • 1: truthy
  • 0: falsy
  • "hello": truthy
  • "": falsy
  • null: falsy
  • {}: truthy
  • []: truthy

Therefore, the sum of truthy values is 6.

It is important to note that the way how different languages treat "true" values may vary, this response assumes the context of javascript.

More questions