calculates the mean age value excluding the missing values represented by the value nan in javascript

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.tsx
let ages = [23, 40, NaN, 19, 25, NaN, 30, 20];
let filteredAges = ages.filter(age => !isNaN(age)); // remove NaN values
let sum = filteredAges.reduce((acc, val) => acc + val); // calculate sum of values
let mean = sum / filteredAges.length; // calculate mean age value

console.log(mean); // output: 26.4
305 chars
7 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