我正在尝试采用此数组:
[
{
"date": a timestamp: June 20, 2020 at 7:32:42 PM UTC
"value": 3
..
}
..
]
并有效地完成三件事
我开始是这样的:
array.sort(function(a,b){ return new Date(b.date) - new Date(a.date);
var salesDates = sales.map(function(element){element.date = new Date(element.date); return element }); })
;
这只会排序,但我需要替换时间戳记/日期,优雅而高效地排序和合并相同的日期
仅sort
功能有可能吗?
这里。首先,我将其分组.reduce()
。然后我整理一下.sort()
。之后,我将时间戳更改为日期格式。
let arr = [
{
"date": 1594023899426,
"value": 3
},
{
"date": 1592423499234,
"value": 2
},
{
"date": 1594023899426,
"value": 1
}
];
let result = arr
.reduce((a, v) => {
let index = a.findIndex(el => el.date === v.date);
if (index !== -1) {
a[index].value += v.value;
return a;
}
a.push({
date: v.date,
value: v.value
});
return a;
}, [])
.sort((a, b) => b.date - a.date)
.map(el => {
el.date = new Date(el.date);
return el;
});
console.log(result);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句