Search code examples
javascriptarraysloopssortingaverage

How do I average the elements that are above a threshold in an array?


I am trying to average all the elements that are above 150 in an array. I can't figure out how to make it all work out and output the correct numbers. Can anyone help?

   function averageBig(list) {
        var sum = 0;
        for (var i = 0; i < list.length && 150; i++) {
            if (list.length > 1000); {
            sum += list[i]
            }
        }    
        return (sum / list.length); 
    }

Solution

  • You can do it like this:

    function averageBig(list) {
        let listFiltered = list.filter(element => element > 150);
        let sum = 0;
        for (let i = 0; i < listFiltered.length; i++) {
                sum += listFiltered[i]
        }    
        return (sum / listFiltered.length);
    }
    

    This filters the list to get only the elements that are over 150 and stores it in a variable called listFiltered. This then loops through all of these values and compares it against the new listFiltered length. If you try to average it based on the initial list length you will be using a length which is also containing values under 150 and therefore skewing the results.