How can i find median values from array in javascript
this is my array
var data = [
{ values: 4 },
{ values: 4 },
{ values: 4 }
This will do what you need - at the moment you've no logic to cope with reading the .values
field out of 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've padded out the code a bit compared to my original answer for readability, and included the (surprising to me) convention that the median of an even-length set be the average of the two elements either side of the middle.