Suppose, we have an array of mixed data types like this −
const arr = [1,2,3,4,5,"4","12","2",6,7,"4",3,"2"];
We are required to write a JavaScript function that takes in one such array and returns the average of all such elements that are a number or can be partially or fully converted to a number.
The string "3454fdf", isn't included in the problem array, but if it wasn’t there, we would have used the number 3454 as its contribution to average.
Example
The code for this will be −
const arr = [1,2,3,4,5,"4","12","2",6,7,"4",3,"2"]; const calculateAverage = arr => { let sum = 0, count = 0; for(let i = 0; i < arr.length; i++){ const val = parseInt(arr[i]); if(val){ sum += val; count++; }; }; return (sum / count); }; console.log(calculateAverage(arr));
Output
And the output in the console will be −
4.230769230769231