數字陣列最值,總和,平均,中位數 未完待續

hy_發表於2019-05-12

// 獲取數字陣列的最小值export const min = arr => arr.sort((x, y) => x -y)[0];// 獲取數字陣列的最大值export const max = arr => arr.sort((x, y) => x -y)[arr.length - 1];// 獲取數字陣列的總和export const sum = arr => arr.reduce((x, y) => x + y);// 獲取數字陣列的平均數export const avg = arr => (arr.reduce((x, y) => x + y) / arr.length).toFixed(5);// 獲取數字陣列的中位數export const med = arr => {    const sortArr = arr.sort((x, y) => x - y);    if (arr.length % 2 === 0) {        return arr.slice(arr.length / 2 - 1, arr.length / 2 + 1).reduce((x, y) => x + y) / 2;    } else {        return sortArr[Math.floor(arr.length / 2)];    }}複製程式碼

存到一個js檔案中,在其他檔案中import { min, max, sum, avg, med } from 'lib/utils';即可


相關文章