javascript - 如何对年份进行分组并减少对象?

标签 javascript

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

当前股息变量为:

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 由于错误而不允许我发帖

最佳答案

您可以使用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; }

关于javascript - 如何对年份进行分组并减少对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54625343/

相关文章:

javascript - 从 jQuery 中隐藏 Bootstrap 模式第一次不起作用

javascript - 如何使用正则表达式分割字符串并仅获取关键部分?

javascript - 如何在 Samsung Tizen Gear s2 中使用边框滚动列表中的项目?

javascript - 使用 node.js 将多个文档插入到 Mongodb

javascript - JS : inject a button next to IP address

javascript - 当使用 jQuery 选择元素时,如何获取元素的普通属性?

javascript - 使用 Joi,验证 bool 值是否为真

javascript - 如何判断滚轮事件是否发生在带有滚动条的元素上?

javascript - async.whilst 中的 callback 和 err 是做什么用的?

javascript - 字符串化对象时如何防止数字字符串化?