From ccbe7c510a27ae2a85b1fa13cc1f1d8075252919 Mon Sep 17 00:00:00 2001 From: atomiks Date: Wed, 13 Dec 2017 10:03:49 +1100 Subject: [PATCH] Create median-of-array-of.md --- snippets/median-of-array-of.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 snippets/median-of-array-of.md diff --git a/snippets/median-of-array-of.md b/snippets/median-of-array-of.md new file mode 100644 index 000000000..0a9c4eab2 --- /dev/null +++ b/snippets/median-of-array-of.md @@ -0,0 +1,17 @@ +### Median of array of numbers + +Find the middle index of an array and sort the numbers in ascending order. If the length of the array is odd, +return the number at the midpoint, otherwise return the average of the two middle numbers. + +```js +const median = numbers => { + const midpoint = Math.floor(numbers.length / 2); + const sorted = numbers.sort((a, b) => a - b); + + return numbers.length % 2 + ? sorted[midpoint] + : (sorted[midpoint - 1] + sorted[midpoint]) / 2; +}; +// median([5,6,50,1,-5]) -> 5 +// median([0,10,-2,7]) -> 3.5 +```