Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

jquery - find median values from array in javascript (8 values or 9 values)

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 value

My 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...