JavaScript; calculate a mean, excluding certain values

PangolinPaws

My question

I have a series of variables populated by satisfaction scores from a survey. These scores are between 1 and 10, but can also be 99 signifying "I don't know".

Without a series of If statements, is is possible to calculate the mean of all the questions while excluding the 99s?

My attempt

Apologies for the slightly odd way question data is retrieved in my example below. Each of the 3 questions has 3 measures which are given a satisfaction rating. The Confirmit survey platform I'm using uses f('x_y').get() to fetch answers where x = question ID and y = measure so f('q3_1').get() returns the score given to the 1st measure in question 3.

var qList = ['q3', 'q4', 'q6']; // 3 questions, each containing 3 satisfaction scores

var output
var i
for (i = 0; i < qList.length; i++){ // For each question in qList...
    // Collect each satisfaction rating & convert to flaoting-point number:
    var sat1 = parseFloat( f(qList[i].concat('_1')).get() );
    var sat2 = parseFloat( f(qList[i].concat('_2')).get() );
    var sat3 = parseFloat( f(qList[i].concat('_3')).get() );

    // Calculate average satisfaction
    var satAvg = (sat1 + sat2 + sat3) / 3;

    if (satAvg == NaN){
        output = "<em>Did not answer</em>";
    } else {
        output = satAvg.toString().concat('/10');
    }

    // Write to open-text questions:
    f('av'.concat(i +1)).set(output)
}

The contents of the open-text av1, av2 & av3 questions populated by the above are concatenated into an email alert, keeping this alert short is why an average is required. Obviously having any "I don't know" responses is going to affect this mean.

EDIT: Based on @Cimbali's answer below, I'm now putting the values into an array. This means unwanted answers (11 & blanks) can be excluded by a single if statement in a loop:

var qList = ['q3', 'q4', 'q6'];

// Get satisfaction scores:
var i;
for (i = 0; i < qList.length; i++){
    var answers = [
        parseFloat( f(qList[i].concat('_1')).get() ),
        parseFloat( f(qList[i].concat('_2')).get() ),
        parseFloat( f(qList[i].concat('_3')).get() )
    ];

    // Remove "I don't know" (11) and blank answers:
    var y;
    for (y = 0; y < answers.length; y++){
        if ( answers[y] > 10 || isNaN(answers[y]) ){
            answers.splice(y, 1);
        }
    }

    // Calculate sum of remaining answers:
    var sum = 0;
    var x;
    for (x = 0; x < answers.length; x++){
        sum += answers[x];
    }

    // Calculate mean:
    var average = sum / answers.length;

    if ( isNaN(average) ){
        // If mean couldn't be calculated, just enter 'N/A':
        var output = "N/A"; 
    } else {
        // Round to 2 decimal places & add the '/10':
        var output = average.toFixed(2).concat("/10");
    }   

    // Write to open text questions:
    f('av'.concat(i +1)).set(output);
}

However, I'm still interested to know of a quicker way.

Cimbali

Try putting them in an array and filtering the array.

Something like:

function validAnswer(n) { return !isNaN(n) && n <= 10; }
answers = [
    parseFloat( f(qList[i].concat('_1')).get() ),
    parseFloat( f(qList[i].concat('_2')).get() ),
    parseFloat( f(qList[i].concat('_3')).get() )
].filter(validAnswer);

answers now contains only the valid answers. Sum the array's contents and divide by its length to get the average. Remember you might have no valid answers at all.

This will make even more sense with a bigger array, in which case you'll probably want to fill the array with a loop rather than hardcoded like this.

function validAnswer(n) { return !isNaN(n) && n <= 10; }

// use functions to populate the array, hardcoded for the example
answers = [1, 2, 11, "not a valid number", 10].filter(validAnswer);
average = answers.length > 0 ? answers.reduce((val, sum) => val + sum) / answers.length: "N/A";

console.log("valid answers are [" + answers + "], average = " + average);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Calculate the mean of a row excluding certain columns in R

From Dev

Calculate the mean across rows excluding min and max values?

From Dev

Calculate dataframe mean by skipping certain values in Python / Pandas

From Dev

Calculate the average excluding some values

From Dev

Calculate mean of calculated values

From Dev

Calculate mean difference values

From Dev

Calculate the mean of values in a loop

From Dev

Finding the mean of certain values

From Dev

Javascript object map calculate the count of keys with values in a certain range

From Dev

Oracle regex_replace is not excluding certain values

From Dev

Concatenate columns inside ArrayFormula, excluding certain values

From Dev

Generate a Point object randomly excluding certain values

From Dev

calculate mean only when the number of values in each rows is higher then certain number in python pandas

From Dev

Group_by with a twist. Calculate mean or certain rows values with zeros for the rest of the rows

From Dev

Calculate days excluding weekend and holiday in JavaScript

From Dev

Calculate group mean while excluding current observation using dplyr

From Dev

Calculate the Mean of the Row in a Data Frame excluding 0 in R

From Dev

Calculate the mean values if the numbers are same

From Dev

calculate mean of certain arrays inside the large array

From Dev

Calculate mean of certain part of numpy array (image)

From Dev

Excluding Columns of a pandas dataframe based on row mean values

From Dev

How to calculate average from a dropdown excluding the "N/A" values

From Dev

Enforce "keyof object", excluding keys whose values are not a certain type

From Dev

Excluding certain numeric values from all columns in queries

From Dev

Determine sum of numpy array while excluding certain values

From Dev

How to calculate mean of every three values of a list

From Dev

Calculate mean for each row containing lists of values

From Dev

Calculate mean of HashMap values after insertion

From Dev

Calculate mean change in values one day later

Related Related

  1. 1

    Calculate the mean of a row excluding certain columns in R

  2. 2

    Calculate the mean across rows excluding min and max values?

  3. 3

    Calculate dataframe mean by skipping certain values in Python / Pandas

  4. 4

    Calculate the average excluding some values

  5. 5

    Calculate mean of calculated values

  6. 6

    Calculate mean difference values

  7. 7

    Calculate the mean of values in a loop

  8. 8

    Finding the mean of certain values

  9. 9

    Javascript object map calculate the count of keys with values in a certain range

  10. 10

    Oracle regex_replace is not excluding certain values

  11. 11

    Concatenate columns inside ArrayFormula, excluding certain values

  12. 12

    Generate a Point object randomly excluding certain values

  13. 13

    calculate mean only when the number of values in each rows is higher then certain number in python pandas

  14. 14

    Group_by with a twist. Calculate mean or certain rows values with zeros for the rest of the rows

  15. 15

    Calculate days excluding weekend and holiday in JavaScript

  16. 16

    Calculate group mean while excluding current observation using dplyr

  17. 17

    Calculate the Mean of the Row in a Data Frame excluding 0 in R

  18. 18

    Calculate the mean values if the numbers are same

  19. 19

    calculate mean of certain arrays inside the large array

  20. 20

    Calculate mean of certain part of numpy array (image)

  21. 21

    Excluding Columns of a pandas dataframe based on row mean values

  22. 22

    How to calculate average from a dropdown excluding the "N/A" values

  23. 23

    Enforce "keyof object", excluding keys whose values are not a certain type

  24. 24

    Excluding certain numeric values from all columns in queries

  25. 25

    Determine sum of numpy array while excluding certain values

  26. 26

    How to calculate mean of every three values of a list

  27. 27

    Calculate mean for each row containing lists of values

  28. 28

    Calculate mean of HashMap values after insertion

  29. 29

    Calculate mean change in values one day later

HotTag

Archive