我有{/ {1}}格式的价格/日期数据
[date, price]
我想知道一种干净的方法来使用lodash或map或类似的东西来获取这样的列表,并根据相同的日期将其合并,例如...
let priceData = [
[1551052800000, 0.33739737955243454]
[1551139200000, 0.33628886196814234]
[1551225600000, 0.12674156277665535]
[1551312000000, 0.16847247989576378]
[1557792000000, 0.5650889670671049]
[1557878400000, 0.6003006017008962]
[1557964800000, 0.6438789432408669]
[1558051200000, 0.6684895789112406]
]
我用一下矩来满足所有日期格式需求。也许有一种整合时刻的方法,例如像他们的// the data below may not be accurate, the point here is the structure
let exampleChuckedData = [
[
[1551052800000, 0.33739737955243454]
[1551139200000, 0.33628886196814234]
[1551225600000, 0.12674156277665535]
[1551312000000, 0.16847247989576378]
]
[
[1557792000000, 0.5650889670671049]
[1557878400000, 0.6003006017008962]
[1557964800000, 0.6438789432408669]
[1558051200000, 0.6684895789112406]
]
]
// Or more conceptually
// Grouped by same date
let exampleConceptData = [
[
['01/01/2019', 0.33739737955243454]
['01/01/2019', 0.33628886196814234]
['01/01/2019', 0.12674156277665535]
['01/01/2019', 0.16847247989576378]
]
[
['01/02/2019', 0.5650889670671049]
['01/02/2019', 0.6003006017008962]
['01/02/2019', 0.6438789432408669]
['01/02/2019', 0.6684895789112406]
]
]
答案 0 :(得分:1)
您可以在对象上使用moment来按日期堆积数据:
步骤1:只是创建一些虚拟数据以供使用
const moment = require('moment');
const data = [];
for(let i = 0; i<1500; i++){
let timestamp = moment().add(i, 'hours').format('X');
data.push([timestamp, Math.random()*10000]);
}
所以现在有了一个带有时间戳和随机数数据的数组。
第2步:让我们按天堆叠。
在这种情况下,对象会更优雅,因为您可以为保存数组的键指定日期。由于javascript比遍历数组以找到匹配的值可以更快地找到对象键,因此这提供了更快的比较机制。
let stacked = {};
for(let item of data){
// Convert timestamp to nice format of string date
const key = moment.unix(`${item[0]}`).format('YYYY-MMM-D');
// If already exists just add it to the object key:value by first spreading what was there and then adding the new item.
if(stacked[key]){
stacked[key] = [...stacked[key], item];
} else {
// If new then set it from the start.
stacked[key] = [item];
}
}
就是这样,您的数据按照这种结构中的日期按对象排序:
data: {
day1: [
[100, 200],
[101, 200]
],
day2: [
[200, 200],
[201, 200]
]
//...
}
答案 1 :(得分:1)
您可以使用_.groupBy()
,然后在回调中使用moment(date).day()
将每个日期转换为一天。使用_.values()
将组的对象转换为数组:
const priceData = [[1551052800000,0.33739737955243454],[1551139200000,0.33628886196814234],[1551225600000,0.12674156277665535],[1551312000000,0.16847247989576378],[1557792000000,0.5650889670671049],[1557878400000,0.6003006017008962],[1557964800000,0.6438789432408669],[1558051200000,0.6684895789112406]]
const result = _.values(_.groupBy(priceData, ([d]) => moment(d).startOf('day')
))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.js"></script>