Find median values ​​from an array in javascript (8 values ​​or 9 values)

How to find median values ​​from an array in javascript

this is my array

var data = [ { values: 4 }, { values: 4 }, { values: 4 }, { values: 5 }, { values: 2 }, { values: 6 }, { values: 6 }, { values: 5 } ]; 

and i tried this code

  function findMedian(m) { var middle = m.length - 1 / 2; if (m.length - 1 % 2 == 1) { return m[middle]; } else { return (m[middle - 1] + m[middle]) / 2.0; } } 

But it returns NaN value

My calculation formula

Find the median of the data. Put the amount of data in ascending order. Then mark the place whose value we take into account when calculating the median.

+6
source share
4 answers

This will do what you need - at the moment you do not have the logic to handle reading the .values field from each element of the array:

 function findMedian(data) { // extract the .values field and sort the resulting array var m = data.map(function(v) { return v.values; }).sort(function(a, b) { return a - b; }); var middle = Math.floor((m.length - 1) / 2); // NB: operator precedence if (m.length % 2) { return m[middle]; } else { return (m[middle] + m[middle + 1]) / 2.0; } } 

EDIT I changed the code a bit compared to my original answer to readability and included (unexpectedly for me) the convention that the median of an even-numbered set is the average of two elements on either side of the middle.

+11
source

Here are two things you should be careful about.

1) Operator Priority

When you speak

 var middle = m.length - 1 / 2; 

This is the same as

  var middle = m.length - 0.5; //Because / has much precedence than - 

So you have to say

  var middle = (m.length - 1) / 2; 

Same problem with m.length - 1 % 2

2) You do not round middle to look for decimal indices in an array. Which, I think, will return undefined .

+5
source

For an array of numbers, for example. [1,6,3,9,28,...]

 // calculate the median function median(arr){ arr = arr.sort(function(a, b){ return a - b; }); var i = arr.length / 2; return i % 1 == 0 ? (arr[i - 1] + arr[i]) / 2 : arr[Math.floor(i)]; } 

What the code does:

  • Sort the numbers so that they are in order by value.
  • Find the average index in the array. If the length of the array is even, the median is the average of two numbers on either side of the index.
  • For arrays of odd length it is easy to cut the average. But for arrays of even length, this is not so. So, you check to see if your array is odd or even long-lived by finding out whether the length of the array will divide by two numbers into an integer or not. If it is an integer, it means that the length of the array is even, and you need to calculate the average of two numbers on either side of the median.

In your question, your array can be flattened as follows:

 var myArray = data.map(function(d){ return d.values; }); 

And to get the median, use the function above:

 var myMedian = median(myArray); // 4.5 
+4
source

Here is a snippet that allows you to create an array of numbers with even or odd lengths. Then the fragment sorts the array and calculates the median, finally printing the sorted array and median.

 (function() { function makeNumArray(isEven) { var randomNumArr = []; var limit = isEven ? 8 : 9; for (var i = 0; i < limit; i++) { randomNumArr.push(Math.ceil(Math.random() * 10)); } return randomNumArr; } function getMedian(arrOfNums) { var result = []; var sortedArr = arrOfNums.sort(function(num1, num2) { return num1 - num2; }); result.push("sortedArr is: [" + sortedArr.toString() + "]"); var medianIndex = Math.floor(sortedArr.length / 2); if (arrOfNums.length % 2 === 0) { result.push((sortedArr[medianIndex-1] + sortedArr[medianIndex]) / 2); return result; } else { result.push(sortedArr[medianIndex]); return result; } } function printMedian(resultArr) { var presentDiv = document.querySelector('#presentResult'); var stringInsert = '<div id="sortedArrDiv">' + resultArr[0].toString() + '<br>' + 'the median is: ' + resultArr[1].toString() + '</div>'; if (!document.querySelector('#sortedArrDiv')) { presentDiv.insertAdjacentHTML('afterbegin', stringInsert); } else { document.querySelector('#sortedArrDiv').innerHTML = resultArr[0].toString() + "<br>" + 'the median is: ' + resultArr[1].toString(); } }; function printEven() { printMedian(getMedian(makeNumArray(1))); } function printOdd() { printMedian(getMedian(makeNumArray(0))); } (document.querySelector("#doEven")).addEventListener('click', printEven, false); (document.querySelector("#doOdd")).addEventListener('click', printOdd, false); })(); 
 #presentResult { width: 70%; margin: 2% 0; padding: 2%; border: solid black; } 
 <h4>Calculate the median of an array of numbers with even (static length of 8) or odd (static length of 9) length. </h4> <input type="button" value="Even length array of random nums" id="doEven"> <input type="button" value="Odd length array of random nums" id="doOdd"> <div id="presentResult"></div> 
0
source

Source: https://habr.com/ru/post/973810/


All Articles