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; }
推荐阅读
- tsql - SSMS - 自动完成参数(智能感知)
- r - R:堆叠条形图的ggplot,绘图和自动调整
- javascript - Javascript:如何在新窗口中安全地打开用户提供的 URL
- java - 在 Hibernate Query 中为一个特定属性生成错误
- angularjs - 当我从数据库中获取轴值时,Highchart 不工作
- javascript - 禁用输入范围的键盘使用
- python - 使用 Seaborn 分割小提琴图和调色板
- node.js - 检查 Firebase 用户是否存在且未引发错误
- swift - 使用 Swift 4 用非素数向下三角求和
- ios - 如何根据文本字段上选定的日期选择器打印年龄?