代码之家  ›  专栏  ›  技术社区  ›  Jim

将插入的零插入到javascript中的日期数组中

  •  2
  • Jim  · 技术社区  · 7 年前
    ]](二)

    我需要在1月16日到1月30日的结束日期之间添加额外的 array(2) values into the map variable for all the days that are missing between jan 16 and the end date of jan 30.

    地图包含:

    enter image description here

    Array(2) 价值观 map

    2 回复  |  直到 7 年前
        1
  •  0
  •   Leonid Pyrlia    7 年前

    假设一天中的时间是相同的,并且基于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]]));
    
        2
  •  1
  •   Nenad Vracar    7 年前

    getDate reduce

    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]];
    });
    
    var result = map.reduce((r, [e], i, arr) => {
      if (i != 0) {
        let date = e.getDate();
        let prev = arr[i - 1][0].getDate();
        r.push(...Array(date - prev - 1).fill(0))
      }
      r.push([e]);
      return r;
    }, [])
    
    
    console.log(result)