Calculating excluded average - JavaScript

In JavaScript, you may need to calculate the average of specific values in an array of objects based on certain conditions. This tutorial shows how to compute the average of values where a boolean flag indicates they should be included in the calculation.

Problem Description

Given an array of objects with val and canUse properties, we need to calculate the average of val values only for objects where canUse is true.

const arr = [
   {val: 56, canUse: true},
   {val: 16, canUse: true},
   {val: 45, canUse: true},
   {val: 76, canUse: false},
   {val: 45, canUse: true},
   {val: 23, canUse: false},
   {val: 23, canUse: false},
   {val: 87, canUse: true},
];

Using Traditional For Loop

const arr = [
   {val: 56, canUse: true},
   {val: 16, canUse: true},
   {val: 45, canUse: true},
   {val: 76, canUse: false},
   {val: 45, canUse: true},
   {val: 23, canUse: false},
   {val: 23, canUse: false},
   {val: 87, canUse: true},
];

const excludedAverage = arr => {
   let count = 0, props = 0;
   for(let i = 0; i 

49.8

Using Array Methods (Modern Approach)

const arr = [
   {val: 56, canUse: true},
   {val: 16, canUse: true},
   {val: 45, canUse: true},
   {val: 76, canUse: false},
   {val: 45, canUse: true},
   {val: 23, canUse: false},
   {val: 23, canUse: false},
   {val: 87, canUse: true},
];

const excludedAverageModern = arr => {
   const usableItems = arr.filter(item => item.canUse);
   const sum = usableItems.reduce((acc, item) => acc + item.val, 0);
   return usableItems.length > 0 ? sum / usableItems.length : 0;
};

console.log(excludedAverageModern(arr));
49.8

How It Works

The calculation includes only objects where canUse: true:

  • Values included: 56, 16, 45, 45, 87
  • Sum: 56 + 16 + 45 + 45 + 87 = 249
  • Count: 5 items
  • Average: 249 รท 5 = 49.8

Comparison

Method Readability Performance Modern JS
For Loop Good Faster Traditional
Array Methods Excellent Slightly slower Modern

Conclusion

Both approaches effectively calculate conditional averages. The traditional for loop offers better performance, while array methods provide cleaner, more readable code for modern JavaScript development.

Updated on: 2026-03-15T23:18:59+05:30

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements