找到在JavaScript数组中值(8个值或9的值) [英] find median values from array in javascript (8 values or 9 values)
问题描述
我怎样才能找到数组中的javascript中值
这是我的数组
VAR数据= [
{值:4},
{值:4},
{值:4},
{值:5},
{值:2},
{值:6},
{值:6},
{值:5}
];
和我已经试过这code
函数findMedian(M){
变种中间= m.length - 1 /;
如果(m.length - 1%2 == 1){
返回M [中];
}其他{
回报(米[中间 - 1] + M [中])/ 2.0;
} }
但它的回报率 NaN的
值
我的计算公式为
查找数据的中位数。放置在升序数据的数量。然后,标志着其值计算中位数时,我们考虑到的地方。
块引用>解决方案这会做你需要的东西 - 此刻你已经没有逻辑,以应对读
.values
现场出数组的每个元素的:函数findMedian(数据){ //提取.values场和结果数组排序
变种M = Data.Map中(函数(五){
返回v.values;
})排序(功能(A,B){
返回 - B;
}); 变种中间= Math.floor((m.length - 1)/ 2); //注意:操作员precedence
如果(m.length%2){
返回M [中];
}其他{
返程(M [中] + M [中等+ 1])/ 2.0;
}
}修改我已经填补了codea的位相比,我原来的答复为便于阅读,并且包括(令我感到诧异)约定偶数长度集的中位数是平均两个元素或者中间的一面。
How can i find median values from 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 have 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's return
NaN
valueMy calculation formula is
Find the median of the data. Place the number of data in ascending order. Then, mark the place whose value we take into account when calculating the median.
解决方案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.
这篇关于找到在JavaScript数组中值(8个值或9的值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!