Calculate median

    0

    0

    Giovanny Gongora

    Codiga's TypeScript Recipes

    Calculates the median of an array of numbers.

    const median = (arr: Array<number>) => {
      const mid: number = Math.floor(arr.length / 2),
        nums: Array<number> = [...arr].sort((a, b) => a - b);
      return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
    };
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.