gpt4 book ai didi

javascript - 如何在具有重复属性名称的对象中获取最大属性值?

转载 作者:行者123 更新时间:2023-11-29 17:34:46 26 4
gpt4 key购买 nike

假设我有一个包含以下值的数组:

数组名称是“subscribers”

1: {month: "2019-07-24", subs: 2}
2: {month: "2019-07-31", subs: 3}
3: {month: "2019-08-01", subs: 2}
4: {month: "2019-08-02", subs: 3}
5: {month: "2019-08-05", subs: 3}
6: {month: "2019-08-08", subs: 4}
7: {month: "2019-08-14", subs: 5}
8: {month: "2019-08-20", subs: 7}
9: {month: "2019-08-23", subs: 7}
10: {month: "2019-08-28", subs: 8}
11: {month: "2019-08-29", subs: 11}
12: {month: "2019-09-02", subs: 2}
13: {month: "2019-09-03", subs: 2}
14: {month: "2019-09-04", subs: 3}
15: {month: "2019-09-05", subs: 5}
16: {month: "2019-09-06", subs: 5}
17: {month: "2019-09-09", subs: 6}
18: {month: "2019-09-10", subs: 7}
19: {month: "2019-09-11", subs: 8}
20: {month: "2019-09-12", subs: 9}

我的问题是,如何才能按月获得最高订阅量?

预期输出:

0: {month: "July", subs: 3}
1: {month: "August", subs: 11}
2: {month: "September", subs: 9}

我尝试使用 array.map,但无法获得预期的输出。我也尝试使用 Math.max,但我似乎无法在对象中使用它。

var getMonthlyValues = subscribers.map(value => {   
var obj = {};
var dateName = new Date(value.period).toLocaleString('default', { month: 'long' });
obj = {month:dateName, subs:value.monthly}
return obj;
})

我可以这样做,例如,如果这些来自数据库,列为月和子,具有它们各自的值。但是我如何在纯 JS 上执行此操作?

最佳答案

你可以拿一个Map ,并收集每个 month 的最大 subs

步骤:

  • 通过将 Map 作为累加器并将分组属性 month 作为键来减少数组。作为值,从先前存储的值或零和实际值中取最大值。

    如果负值或零可用,请使用 conditional (ternary) operator ?: , 喜欢

      m.has(month) ? Math.max(m.get(month), subs) : subs
  • 获取键/值对列表并返回具有自定义命名属性的对象数组 Array.from和一个映射函数。

var data = [{ month: "July", subs: 2 }, { month: "July", subs: 3 }, { month: "August", subs: 2 }, { month: "August", subs: 3 }, { month: "August", subs: 3 }, { month: "August", subs: 4 }, { month: "August", subs: 5 }, { month: "August", subs: 7 }, { month: "August", subs: 7 }, { month: "August", subs: 8 }, { month: "August", subs: 11 }, { month: "September", subs: 2 }, { month: "September", subs: 2 }, { month: "September", subs: 3 }, { month: "September", subs: 5 }, { month: "September", subs: 5 }, { month: "September", subs: 6 }, { month: "September", subs: 7 }, { month: "September", subs: 8 }, { month: "September", subs: 9 }],
result = Array.from(
data.reduce(
(m, { month, subs }) => m.set(month, Math.max(m.get(month) || 0, subs)),
new Map
),
([month, subs]) => ({ month, subs })
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何在具有重复属性名称的对象中获取最大属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57900922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com