forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAverageMedian.js
More file actions
Latest commit
22 lines (18 loc) · 799 Bytes
/
Copy pathAverageMedian.js
File metadata and controls
22 lines (18 loc) · 799 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
* Median: https://en.wikipedia.org/wiki/Median
*
* function averageMedian
* to find the median value of an array of numbers
* the numbers in an array will be sorted in ascending order by the function sortNumbers
* if the length of the array is even number, the median value will be the average of the two middle numbers
* else if the length of the array is odd number, the median value will be the middle number in the array
*/
constaverageMedian=(sourceArrayOfNumbers)=>{
constnumbers=[...sourceArrayOfNumbers].sort(sortNumbers)
constnumLength=numbers.length
returnnumLength%2===0
? (numbers[numLength/2-1]+numbers[numLength/2])/2
: numbers[Math.floor(numLength/2)]
}
constsortNumbers=(num1,num2)=>num1-num2
export{averageMedian}