r/GoogleAppsScript • • May 26 '21

Question Average excluding Highest and Lowest values

Hello,

need to create a custom function (to be used in Google sheets) that calculates average excluding highest and lowest values included in any range

for example Range ( 1 2 3 4 5 6 ) function to exclude 1 and 6 and calculates average of ( 2 3 4 5 )

so I think it can conclude sum(range) - max(range) - min(range) /count(range) -2

Thanks in Advance :)

6 Upvotes

8 comments sorted by

3

u/TobofCob May 26 '21

Here you go! Sorry if any formatting issues. I commented the code to be more readable. This will check that all values are integers, then will remove min and max values, then will return the average.

function avgExceptMinMax(range) {
  values = range.flat() // flatten range to a single list if multi-line range is given
  if(!values.every( e  => !isNaN(parseInt(e)))) { // checks if all values in list are numbers
    throw new Error ("All values in range must be a number");
  }
  var max = Math.max(...values);  // determines the min/max values
  var min = Math.min(...values);
  var minIdx = values.indexOf(max);  // determines the index of the min/max value
  var maxIdx = values.indexOf(min);
  values.splice(minIdx,1)  // removes the min/max values from the list
  values.splice(maxIdx,1);
  var sum = values.reduce((a, b) => a + b, 0);  // determines sum of remaining values in list
  var avg = (sum / values.length) || 0  //defaults to zero if empty range is given
  return avg
}

2

u/sherifzorkani May 26 '21

TypeError: Cannot read property 'flat' of undefined

avgExceptMinMax

@ Code.gs:2

2

u/RemcoE33 May 26 '21

U use it like a normal function:

=avgExceptMinMax(E2:E10)

2

u/TobofCob May 26 '21

This. Don’t call the function in Apps Script, reference the range you want to use it on in the sheet itself and let it do the rest! If you’re still getting that error though let me know and I will debug if needed.

2

u/sherifzorkani May 26 '21

my function is =iferror(average('Judge 1'!E10,'Judge 2'!E10,'Judge 3'!E10,'Judge 4'!E10,'Judge 5'!E10,'Judge 6'!E10,'Judge 7'!E10,'Judge 8'!E10,'Judge 9'!E10,'Judge 10'!E10),"") I need to exclude the highest and lowest value

1

u/sherifzorkani May 27 '21

I do rely on many sheets

1

u/paulcole710 May 27 '21 edited May 27 '21

What if the values are (1,1,1,2,3,4,5,6,6,6)?

Remove every 1 and every 6 or just one of each?

What about (1,2) or (1,1,1,1,1)?

Does the former return anything? Does the latter return 1 or nothing at all?

0

u/sherifzorkani May 27 '21

only 1 and 6