如何在JavaScript中为对象数组的每个作者单独计算阅读时长中位数
实现思路
你只需要先按作者分组收集所有对应readingTime数值,再对每个分组调用你已封装的中位数计算函数即可,完整可运行代码如下:
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}] // 你已实现的中位数计算函数 function medianof2Arr(arr1) { var concat = arr1; concat = concat.sort(function (a, b) { return a - b }); var length = concat.length; if (length % 2 == 1) { return concat[(length / 2) - .5] } else { return (concat[length / 2] + concat[(length / 2) - 1]) / 2; } } // 按作者分组计算中位数的实现 function getAuthorReadingMedian(bookList) { // 1. 按作者分组收集readingTime const authorReadingMap = {} bookList.forEach(book => { if (!authorReadingMap[book.author]) { authorReadingMap[book.author] = [] } authorReadingMap[book.author].push(book.readingTime) }) // 2. 遍历分组计算每个作者的中位数 const medianResult = {} Object.keys(authorReadingMap).forEach(author => { const medianVal = medianof2Arr(authorReadingMap[author]) // 若需要和你给出的预期输出完全一致(对小数取整),可改为 medianResult[author] = Math.round(medianVal) medianResult[author] = medianVal }) return medianResult } // 测试输出 console.log(getAuthorReadingMedian(bookDetails)) // 直接输出结果:{"john": 1890, "romero": 365, "buck": 7013.5, "legend": 12} // 对buck的7013.5执行Math.round后即可得到你预期的7014
结果验证说明
- 作者john的
readingTime排序后为[10, 1890, 12123],长度为奇数,中位数就是中间值1890 - 作者romero的
readingTime排序后为[50, 189, 230, 500, 908, 1212],长度为偶数,中位数为(230+500)/2=365 - 作者buck的
readingTime排序后为[1902, 12125],中位数为(1902+12125)/2=7013.5,取整后为7014 - 作者legend的
readingTime只有一个值12,中位数就是12
内容的提问来源于stack exchange,提问作者Siva Pradhan
相关产品推荐
相关产品推荐

