如何在JS中弹出特定日期之前的数组值

所以我正在使用一个视频游戏的 api,它返回公会成员 exp 对象:


"expHistory": {

                "2020-11-26": 84825,

                "2020-11-25": 87219,

                "2020-11-24": 44447,

                "2020-11-23": 14849,

                "2020-11-22": 57379,

                "2020-11-21": 32364,

                "2020-11-20": 42295

            }

我需要确定每个成员的所有公会经验的总价值,但是我只想包括周一之后获得的经验。我有一个非常糟糕的系统,它可以工作,但经常由于各种原因而崩溃。任何见解将不胜感激。


长风秋雁
浏览 46回答 1
1回答

繁星淼淼

我们可以使用Object.entries、Array.filter和Array.reduce来计算所需日期范围的总分。我们只需要输入正确的日期阈值:let obj = {     "expHistory": {        "2020-11-26": 84825,        "2020-11-25": 87219,        "2020-11-24": 44447,        "2020-11-23": 14849,        "2020-11-22": 57379,        "2020-11-21": 32364,        "2020-11-20": 42295    }}            function getTotal(thresholdDate, expHistory) {    let result = Object.entries(expHistory)        .filter(([date, points]) => date > thresholdDate)        .reduce((total, [date, points]) => total + points, 0);    return result;} const thresholdDate = "2020-11-20";console.log(`Total (from ${thresholdDate}):`, getTotal(thresholdDate, obj.expHistory));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript