To calculate the mean age of values in a Javascript array while excluding NaN
(missing) values, you can use the Array filter()
and reduce()
methods as follows:
index.tsx305 chars7 lines
First, we create an array of ages that includes NaN
values. We then use the filter()
method to remove all NaN
values, leaving only the valid ages. We store the filtered array in filteredAges
.
Next, we use the reduce()
method to calculate the sum of all values in the filteredAges
array. We start with an initial value of 0
for the accumulator and add the value of each element in the array using the arrow function.
Finally, we calculate the mean age value by dividing the sum by the length of the filteredAges
array. The result is stored in the mean
variable and printed to the console.
Note that the isNaN()
function is used to check if a value is NaN
. This function returns false
for valid numbers and true
for NaN
. Using the logical NOT operator (!
) in the arrow function passed to filter()
will remove all NaN
values from the array.
gistlibby LogSnag