
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Are Mean and Mode of a Dataset Equal in JavaScript?
We are required to write a JavaScript function that takes in an array of sorted numbers. The function should calculate the mean and the mode of the dataset. Then if the mean and mode are equal, the function should return true, false otherwise.
For example −
If the input array is −
const arr = [5, 3, 3, 3, 1];
Then the output for this array should be true because both the mean and median of this array are 3.
Example
Following is the code −
const arr = [5, 3, 3, 3, 1]; mean = arr => (arr.reduce((a, b) => a + b))/(arr.length); mode = arr => { let obj = {}, max = 1, mode; for (let i of arr) { obj[i] = obj[i] || 0; obj[i]++ } for (let i in obj) { if (obj.hasOwnProperty(i)) { if ( obj[i] > max ) { max = obj[i] mode = i; } } } return +mode; } const meanMode = arr => mean(arr) === mode(arr) console.log(meanMode(arr));
Output
Following is the output on console −
true
Advertisements