Jasyn Marais

Statistics using JavaScript

Mean

To calculate the mean (average) of an array in JavaScript:

function calculateMean(arr) {
  const n = arr.length;

  if (n === 0) {
    return null; // No elements in the array
  }

  const sum = arr.reduce((total, current) => total + current, 0);
  const mean = sum / n;

  return mean;
}

const numbers = [3, 1, 7, 5, 2, 8, 4, 6];
const mean = calculateMean(numbers);
console.log("Mean:", mean); 

Median

To calculate the median of an array in JavaScript:

function calculateMedian(arr) {
    // Step 1: Sort the array
    arr.sort((a, b) => a - b);
            
    const n = arr.length;
            
    if (n === 0) {
        return null; // No elements in the array
    } else if (n % 2 === 1) {
        // Odd number of elements
        return arr[Math.floor(n / 2)];
    } else {
        // Even number of elements
        const mid1 = arr[n / 2 - 1];
        const mid2 = arr[n / 2];
        return (mid1 + mid2) / 2;
    }
}
          
const numbers = [3, 1, 7, 5, 2, 8, 4, 6];
const median = calculateMedian(numbers);
console.log("Median:", median); 

Mode

To calculate the mode (most frequently occurring value) of an array in JavaScript, you can create a function that counts the occurrences of each unique value in the array and then finds the one with the highest count.

function calculateMode(arr) {
    if (arr.length === 0) {
    return null; // No elements in the array
    }
      
    // Create an object to store value frequencies
    const frequencyMap = {};
      
    // Count the occurrences of each value
      arr.forEach(value => {
        if (frequencyMap[value]) {
          frequencyMap[value]++;
          } else {
            frequencyMap[value] = 1;
            }
        });
      
        let mode = null;
        let maxFrequency = 0;
      
        // Find the mode (value with highest frequency)
        for (const value in frequencyMap) {
          if (frequencyMap[value] > maxFrequency) {
            mode = value;
            maxFrequency = frequencyMap[value];
          }
        }
    return mode;
}
      
const numbers = [3, 1, 7, 5, 2, 8, 4, 6, 3, 7, 3];
const mode = calculateMode(numbers);
console.log("Mode:", mode);

Standard Deviation

To calculate the standard deviation of an array in JavaScript:

function calculateStandardDeviation(arr) {
    const n = arr.length;
      
    if (n === 0) {
          return null; // No elements in the array
    }
      
    // Step 1: Calculate the mean
    const mean = arr.reduce((total, current) => total + current, 0) / n;
      
    // Step 2: Calculate the squared differences from the mean
    const squaredDifferences = arr.map(value => Math.pow(value - mean, 2));
      
    // Step 3: Calculate the mean of squared differences
    const meanSquaredDiff = squaredDifferences.reduce(
      (total, current) => total + current,
      0
    ) / n;
      
    // Step 4: Take the square root of the mean of squared differences
    const standardDeviation = Math.sqrt(meanSquaredDiff);
      
    return standardDeviation;
  }
      
const numbers = [3, 1, 7, 5, 2, 8, 4, 6];
const stdDev = calculateStandardDeviation(numbers);
console.log("Standard Deviation:", stdDev);

Variance

To calculate the variance of an array in JavaScript, you can modify the steps used for calculating the standard deviation slightly. Variance is the average of the squared differences between each value and the mean.

function calculateVariance(arr) {
    const n = arr.length;
      
    if (n === 0) {
      return null; // No elements in the array
    }
      
    // Step 1: Calculate the mean
    const mean = arr.reduce((total, current) => total + current, 0) / n;
      
    // Step 2: Calculate the squared differences from the mean
    const squaredDifferences = arr.map(value => Math.pow(value - mean, 2));
      
    // Step 3: Calculate the mean of squared differences
    const variance = squaredDifferences.reduce(
      (total, current) => total + current,
      0
    ) / n;
      
    return variance;
  }
      
const numbers = [3, 1, 7, 5, 2, 8, 4, 6];
const variance = calculateVariance(numbers);
console.log("Variance:", variance);