首页 > 解决方案 > 如何分组年份和减少对象?

问题描述

我想更新对象以仅显示最近一年,每年仅显示一个。

当前的股息变量是:

const data = {
    0: [
        'AAPL',
        0.378571,
        '2012-09-30'
    ],
    1: [
        'AAPL',
        0.378571,
        '2012-12-31'
    ],
    2: [
        'AAPL',
        0.378571,
        '2013-03-31'
    ],
    3: [
        'AAPL',
        0.435714,
        '2013-09-30'
    ],
    4: [
        'AAPL',
        0.435714,
        '2013-12-31'
    ],
    5: [
        'AAPL',
        0.47,
        '2014-09-30'
    ],
    6: [
        'AAPL',
        0.47,
        '2014-12-31'
    ],
    7: [
        'AAPL',
        0.52,
        '2015-06-30'
    ],
    8: [
        'AAPL',
        0.52,
        '2015-09-30'
    ],
    9: [
        'AAPL',
        0.52,
        '2015-12-31'
    ]
};

我想将变量更新为:

const dividends = {
    0: [
        'AAPL',
        0.378571,
        '2012-12-31'
    ],
    1: [
        'AAPL',
        0.435714,
        '2013-12-31'
    ],
    2: [
        'AAPL',
        0.47,
        '2014-12-31'
    ],
    3: [
        'AAPL',
        0.52,
        '2015-12-31'
    ]
};

抱歉不得不删除代码块格式,因为由于错误,stackoverflow 不允许我发布

标签: javascript

解决方案


您可以使用array#reduce对象中日期最早的年份对数据进行分组。然后使用 获取所有值Object.values()

const data = { 0: [ 'AAPL', 0.378571, '2012-09-30' ], 1: [ 'AAPL', 0.378571, '2012-12-31' ], 2: [ 'AAPL', 0.378571, '2013-03-31' ], 3: [ 'AAPL', 0.435714, '2013-09-30' ], 4: [ 'AAPL', 0.435714, '2013-12-31' ], 5: [ 'AAPL', 0.47, '2014-09-30' ], 6: [ 'AAPL', 0.47, '2014-12-31' ], 7: [ 'AAPL', 0.52, '2015-06-30' ], 8: [ 'AAPL', 0.52, '2015-09-30' ], 9: [ 'AAPL', 0.52, '2015-12-31' ] },
    result = Object.values(data).reduce((r,a) => {
      let year = a[2].substr(0,4);
      r[year] = r[year] || [...a];
      r[year] = r[year][2] > a[2] ? r[year]: [...a];
      return r;
    },{});
const dividends = {...Object.values(result)};
console.log(dividends);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读