Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding average in mixed data type array in JavaScript
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
How It Works
The function uses parseInt() to convert each array element to a number. It extracts the numeric portion from strings and ignores non-numeric characters. The if(val) check filters out NaN and 0 values, then accumulates the sum and count for calculating the average.
Alternative Approach Using filter() and reduce()
const arr = [1,2,3,4,5,"4","12","2",6,7,"4",3,"2"];
const calculateAverageModern = arr => {
const validNumbers = arr
.map(item => parseInt(item))
.filter(num => !isNaN(num) && num !== 0);
const sum = validNumbers.reduce((acc, num) => acc + num, 0);
return sum / validNumbers.length;
};
console.log(calculateAverageModern(arr));
4.230769230769231
Conclusion
Both approaches effectively calculate the average of numeric values in mixed arrays using parseInt(). The modern approach uses array methods for cleaner, more functional code.
