
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Finding average age from array of Objects using JavaScript
- Separating data type from array into groups in JavaScript
- Finding average word length of sentences - JavaScript
- Finding upper elements in array in JavaScript
- Finding peculiar pairs in array in JavaScript
- Finding average of n top marks of each student in JavaScript
- Finding special type of numbers - JavaScript
- Calculating average of an array in JavaScript
- How to sort mixed numeric/alphanumeric array in JavaScript
- Finding special array - JavaScript
- Mixed Pseudo Type in PHP 8
- Finding unlike number in an array - JavaScript
- Finding median index of array in JavaScript
- Finding unique string in an array in JavaScript
- Find average of each array within an array in JavaScript

Advertisements