Are mean 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