在javascript中从数组中查找中值(8个值或9个值) [英] find median values from array in javascript (8 values or 9 values)

查看:50
本文介绍了在javascript中从数组中查找中值(8个值或9个值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在javascript中从数组中找到中值

How can i find median values from array in javascript

这是我的数组

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

我已经试过这个代码

 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;
        }

    }

但它返回NaN

我的计算公式是

求数据的中位数.将数据数量按升序排列.然后,标记我们在计算中位数时考虑其值的地方.

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.

推荐答案

这将满足您的需求 - 目前您没有逻辑来应对从每个字段中读取 .values 字段数组元素:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆