I am trying to find the median of an array. I have done quite some research and if this seemed to be asked several times, no answers were satisfying.
Creating my array works perfectly but when I call the function the array is sorted but it returns different values, from NaN to the first value of the array
How to find the median value of the length, and then from it's index find the median value of the array?
var ar1 = [];
while (true) {
var enterValues = prompt("enter your values");
if (enterValues != "") {
ar1.push(enterValues);
} else {
break;
}
}
function calcMedian() {
var half = Math.floor(ar1.length / 2);
ar1.sort(function(a, b) { return a - b;});
if (ar1.length % 2) {
return ar1[half];
} else {
return (ar1[half] + ar1[half] + 1) / 2.0;
}
}
console.log(ar1);
console.log(ar1.length);
console.log(calcMedian());
console.log(ar1);
(ps:to stop filling the array just enter without value.)
var ar1 = [];
while (true) {
var enterValues = prompt("enter your values");
if (enterValues != "") {
ar1.push(parseFloat(enterValues));
} else {
break;
}
}
function calcMedian() {
var half = Math.floor(ar1.length / 2);
ar1.sort(function(a, b) { return a - b;});
if (ar1.length % 2) {
return ar1[half];
} else {
return (ar1[half-1] + ar1[half]) / 2.0;
}
}
console.log(ar1);
console.log(ar1.length);
console.log(calcMedian());
console.log(ar1);
Math.floor(ar1.length)
will return (for example) 4
is the length is 8
. However, if you do ar1[4]
it will actually return the fifth item in the array as the array index starts at zero. So ar1[4-1]
will return the fourth item, add it to ar1[4]
which is the fifth item and divide it by two to find the median. If the length is odd, it will return (for example) 3
if the length is 7
. It then retrieves arr[3]
which is the fourth item which is the median.