计算对象数组的中位数

西瓦·普拉丹

我有一个对象数组:

const bookDetails = [{"author":"john","readingTime":12123}, 
                     {"author":"romero","readingTime":908}, 
                     {"author":"romero","readingTime":1212}, 
                     {"author":"romero","readingTime":50}, 
                     {"author":"buck","readingTime":1902}, 
                     {"author":"buck","readingTime":12125}, 
                     {"author":"romero","readingTime":500},
                     {"author":"john","readingTime":10},
                     {"author":"romero","readingTime":230}, 
                     {"author":"romero","readingTime":189}, 
                     {"author":"legend","readingTime":12}
                     {"author":"john","readingTime":1890}]

我尝试计算每个作者的中位数。这是我计算给定数组中位数的函数:

//To calculate the median for a given array
function medianof2Arr(arr1) {
    var concat = arr1;
    concat = concat.sort(function (a, b) { return a - b });
    var length = concat.length;

    if (length % 2 == 1) {
        // If length is odd
        return concat[(length / 2) - .5]
    } else {
        return (concat[length / 2] + concat[(length / 2) - 1]) / 2;
    }
}

但我想分别计算每个作者的中位数我怎样才能做到这一点?

预期输出

{"john": 1890, "romero": 365, "buck": 7014, "legend": 12}
特里科特

您可以首先按作者对您的输入进行分组,以获得此数据结构:

{
    "john": [12123, 10, 1890],
    "romero": [908, 1212, 50, 500, 230, 189],
    "buck": [1902, 12125],
    "legend": [12]
}

然后你可以在所有这些数组上调用中值函数,并用你从调用中得到的值替换这些数组:

function median(arr) {
    arr = [...arr].sort((a, b) => a - b);
    let mid = arr.length >> 1;
    return arr.length % 2 ? arr[mid] : (arr[mid-1] + arr[mid]) / 2;
}

const bookDetails = [{"author":"john","readingTime":12123}, {"author":"romero","readingTime":908}, {"author":"romero","readingTime":1212}, {"author":"romero","readingTime":50}, {"author":"buck","readingTime":1902}, {"author":"buck","readingTime":12125}, {"author":"romero","readingTime":500},{"author":"john","readingTime":10},{"author":"romero","readingTime":230}, {"author":"romero","readingTime":189}, {"author":"legend","readingTime":12},{"author":"john","readingTime":1890}];                         
                     
// Create a key for each author, and link them with an empty array
let result = Object.fromEntries(bookDetails.map(({author}) => [author, []]));
// Populate those arrays with the relevant reading times
for (let {author, readingTime} of bookDetails) result[author].push(readingTime);
// Replace those arrays with their medians:
for (let author in result) result[author] = median(result[author]);

console.log(result);

请注意,降压的中位数不是您预期输出中的整数 7014,而是 7013.5

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章