'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 1:[1]
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.
Solution 2:[2]
Average all the items in the list which are greater than 150.
function averageBig(list) {
let sum = 0;
let items = 0;
for (let i = 0; i < list.length; i++) {
if (list[i] > 150) {
sum += list[i];
items++;
}
}
return (sum / items);
}
const numbers = [ 10, 20, 50, 100, 150, 200, 300];
console.log(averageBig(numbers));
console.log((200 + 300) / 2);
Solution 3:[3]
this function return sum of array elements greater than num, you can then simply divide it by arr.length.
function sumGreaterThan(arr, num) {
return arr.reduce((sum, cur) => {
if (cur > num) return sum + cur;
return sum;
}, 0);
}
Solution 4:[4]
to average all the elements that are greater than 150 in an array
Use filter to extract the items > 150
use reduce to sum them
calculate average
const entries = [10,23,151,200,233,244,299,100,123];
const filtered = entries.filter(e=>e > 150);
const sum = filtered => filtered.reduce((a,b) => a + b, 0)
const average = sum(filtered) / (filtered.length);
console.log(average);
Solution 5:[5]
function averageBig(list) {
var sum = 0;
for (var i = 150; i <= list.length; i++) {
sum += list[i]
}
return (sum / list.length);
}
I assume that the 150 you are talking about is the data starting 150th and above.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | General Grievance |
Solution 2 | Michael Rodriguez |
Solution 3 | modos |
Solution 4 | sumit |
Solution 5 | General Grievance |