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

时间:2019-09-12 06:31:27

标签: javascript javascript-objects

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

数组名称为“订户”

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;
    })

例如,如果这些来自数据库,其中列分别为month和sub,并具有各自的值,则可以执行此操作。但是如何在纯JS上做到这一点?

1 个答案:

答案 0 :(得分:4)

您可以拿一个Map,然后为每个subs收集最多month

步骤:

  • 通过使用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; }