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

前端 未结 6 1607
粉色の甜心
粉色の甜心 2020-12-11 16:33

How can i find median values from array in javascript

this is my array

var data = [       
    { values: 4 }, 
    { values: 4 }, 
    { values: 4 }         


        
6条回答
  •  抹茶落季
    2020-12-11 17:05

    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.

提交回复
热议问题