在javascript中向日期数组插入插入的零
给出了一个图表值列表,如下所示在javascript中向日期数组插入插入的零,javascript,Javascript,给出了一个图表值列表,如下所示数组 var arrays = [["A", [ [1391032800000, 20], [1389826800000, 4], [1389913200000, 4], [1390086000000, 6] ] ]];
数组
var arrays = [["A", [
[1391032800000, 20],
[1389826800000, 4],
[1389913200000, 4],
[1390086000000, 6]
]
]];
var dates = arrays[0][1].sort(function(x, y) { return x[0] - y[0]; });
var map = dates.map(function(dt) { return [new Date(dt[0]), dt[1]]; });
console.log(map);
地图包括:
我需要在map
变量中添加额外的Array(2)
值,用于1月16日到1月30日结束日期之间缺少的所有天数
填充数组中缺少的零值(每缺少一天)的最快方法是什么。您可以使用
getDate
方法,然后使用reduce
方法创建新数组,获取两个日期之间的差值,并用零填充差值
var数组=[
[“A”[
[1391032800000, 20],
[1389826800000, 4],
[1389913200000, 4],
[1390086000000, 6]
]]
];
变量日期=数组[0][1]。排序(函数(x,y){
返回x[0]-y[0];
});
var map=dates.map(函数(dt){
返回[新日期(dt[0]),dt[1]];
});
var结果=映射减少((r[e],i,arr)=>{
如果(i!=0){
让date=e.getDate();
设prev=arr[i-1][0].getDate();
r、 推送(…数组(日期-上一个-1)。填充(0))
}
r、 推送([e]);
返回r;
}, [])
console.log(result)
假设一天中的时间相同,并基于Darren Sweeney的建议:
const data = [
[1391032800000, 20],
[1389826800000, 4]
];
// getting min and max dates in the array
const timestamps = data.map(([timestamp]) => timestamp);
const [min, max] = [Math.min(...timestamps), Math.max(...timestamps)];
// creating hash where evrey day in the range between min and max dates has a value of 0
let dataObj = {};
let tempTimestamp = min;
while (tempTimestamp <= max) {
dataObj[tempTimestamp] = 0;
tempTimestamp += 86400000;
}
// lopping through the original array and populating a "zero-valued" hash with values from original array
data.forEach(([timestamp, value]) => {
dataObj[timestamp] = value;
})
// converting a hash into array
const result = Object.keys(dataObj).map(timestamp => ([timestamp, dataObj[timestamp]]));
const数据=[
[1391032800000, 20],
[1389826800000, 4]
];
//获取数组中的最小和最大日期
const timestamp=data.map(([timestamp])=>timestamp);
常量[min,max]=[Math.min(…时间戳),Math.max(…时间戳)];
//正在创建哈希,其中最小日期和最大日期之间的evrey day的值为0
设dataObj={};
设时间戳=min;
while(试印){
dataObj[时间戳]=值;
})
//将散列转换为数组
const result=Object.keys(dataObj.map)(timestamp=>([timestamp,dataObj[timestamp]]);
一天中的时间可能都不同吗?每个数组(2)中的第二个值来自哪里?i、 例如,4,4,6,20values@Darren:否,一天中的时间都应相同,时间组件应为ignored@David第二个值是给定的,我有4天的值。我想为所有未表示的日期(天)添加零。我的做法与您的想法相反-首先创建日期数组(从数组中获取第一个和最后一个日期,然后填充空格),然后在该数组中循环,并在数组中映射值此解决方案,尽管它看起来很棒,但如果您运行它,它不会显示缺失条目的日期,并且会释放值。您说过要为缺失的天数插入0。