简体   繁体   English

Javascript在数组中获取顺序日期

[英]Javascript Get Sequential Dates in Array

I have an array with the following values (example): 我有一个包含以下值的数组(示例):

   [
      1367848800000: true,
      1367935200000: true,
      1368021600000: true,
      1368108000000: true,
      1368194400000: true,
      1368367200000: true,
      1368540000000: true,
      1368626400000: true,
      1368712800000: true
    ]

Where the index is a date time. 索引是日期时间。 The date time will always be at 12:00:00 on a date. 日期时间始终为12:00:00。

In this example, the first five dates are consecutive, then one day by itself, and then another group of 3 dates. 在此示例中,前五个日期是连续的,然后是一天,然后是另一组3个日期。 An example of what I mean is below. 我的意思的一个例子如下。

日历上的日期

Now, what I am trying to do is find sequential dates and put them into an array as follows: 现在,我要做的是查找顺序日期并将它们放入数组中,如下所示:

   [
      1367848800000,
      1367935200000,
      1368021600000,
      1368108000000,
      1368194400000
   ],
   [
      1368367200000,
      1368540000000,
      1368626400000,
   ],
   [
      1368712800000Ω
   ]

So in the end, I have an array, with 3 arrays of all the times. 所以最后,我有一个数组,总共有3个数组。 I have tried numerous pieces of code, but everything bugs out and nothing is worth posting on here. 我已经尝试了很多代码,但是一切都有问题,没有什么值得在这里发布。 Any help would be much appreciated! 任何帮助将非常感激!

The following approach uses array .reduce() method: 以下方法使用数组.reduce()方法:

var arr = [1367848800000, 1367935200000, 1368021600000,
           1368108000000, 1368194400000, 1368367200000,
           1368540000000, 1368626400000, 1368712800000],
    i = 0,
    result = arr.reduce(function(stack, b) {
        var cur = stack[i],
            a = cur ? cur[cur.length-1] : 0;

        if (b - a > 86400000) {
            i++;
        }

        if (!stack[i])
            stack[i] = [];

        stack[i].push(b);

        return stack;
    }, []);

console.log(result);

DEMO: http://jsfiddle.net/gbC8B/1/ 演示: http //jsfiddle.net/gbC8B/1/

Sth like this could do: 这样做可以做到:

  function sequentialize(dArr) {
      dArr = Object.keys(dArr).slice().sort();
      var last;
      var arrs = [[]];

      for (var i = 0, l = dArr.length; i < l; i++) {
          var cur = new Date();
          cur.setTime(dArr[i]);
          last = last || cur;

          if (isNewSequence(cur, last)) {
              arrs.push([]);
          }

          arrs[arrs.length - 1].push(cur.getTime()); //always push to the last index
          last = cur;
      }


      return arrs;


      function isNewSequence(a, b) {
          if (a.getTime() - b.getTime() > (24 * 60 * 60 * 1000))
              return true;
          return false;
      }
  }

Now if you pass your example Array/Object to the sequentialize function 现在,如果您将示例Array/Object传递给sequentialize函数

  var dates = {
      1367848800000: true,
      1367935200000: true,
      1368021600000: true,
      1368108000000: true,
      1368194400000: true,
      1368367200000: true,
      1368540000000: true,
      1368626400000: true,
      1368712800000: true
  };

  console.log(sequentialize(dates));

This gives the following output 这给出了以下输出

  [
      [
          1367848800000,
          1367935200000,
          1368021600000,
          1368108000000,
          1368194400000
      ],
      [
          1368367200000
      ],
      [
          1368540000000,
          1368626400000,
          1368712800000
      ]
  ]

This simply 这很简单

  1. creates an array out of the Date keys, 从Date键创建一个数组,

  2. Sorts them 对它们进行排序

  3. Iterates over them 迭代他们

  4. If the difference of the Current and Last Date is greate than a day 如果当前和最后日期的差异大于一天

  5. Push a new Array to the Sequence Array 将新阵列推送到序列阵列

  6. Push the Current Date to the last Array in the Sequence Array 将当前日期推送到序列阵列中的最后一个数组

    Demo on JSBin 演示JSBin

Note: You may have to change the isNewSequence function to actually fit your needs 注意:您可能必须更改isNewSequence函数才能真正满足您的需求

// Preconditions: singleArray contains the input array with each element corresponding to a time index. singleArray is sorted.

var outputArray = new Array();
var stack = new Array();
var stackSize = 0;

var i;
for( i = 0; i < singleArray.length; i++ )
{
    // Get the last element on the stack
    var lastElement = (stackSize == 0) ? 0 : stack.pop();

    // Compare to see if difference is one day
    if( singleArray[i] - lastElement == 86400000 ) // 24 * 60 * 60 * 1000
    {
        // Dates are 1 day apart
        if( lastElement != 0 ) stack.push(lastElement);
        stack.push(singleArray[i]);
        stackSize++;
    }
    else
    {
        if( lastElement != 0 ) stack.push(lastElement);

        var tempQueue = new Array();
        while(stackSize > 0)
        {
            // Build up a new array containing consecutive days
            // using a queue
            tempQueue.push(stack.pop());
            stackSize--;
        }

        // Push the consecutive days onto the next place in the output array.
        outputArray.push(tempQueue);

        // Start a new group of consecutive dates
        stack.push(singleArray[i]);
        stackSize++;
    }

}

Gotta love these puzzles. 一定要喜欢这些谜题。 Nice answers everyone, here's mine more jQueryish approach. 尼斯回答大家,这里是我的更多jQueryish方法。

var datearray =  {
    1367848800000: true,
    1367935200000: true,
    1368021600000: true,
    1368108000000: true,
    1368194400000: true,
    1368367200000: true,
    1368540000000: true,
    1368626400000: true,
    1368712800000: true
};

$(function() {

    var result = dateSequences(datearray);
}

function dateSequences(array) {
    // parse json object to array of keys
    var keys = Object.keys(array);
    // sort it up
    keys = keys.sort();
    // convert them to dates
    var dates = new Array();
    $.each(keys, function(i) {
        dates.push(new Date(parseInt(keys[i])));
    });

    // now we have array of dates, search for sequential dates
    var final = new Array();
    var prevdate = undefined;
    var currentseq = 0;    
    $.each(dates, function(i, d) {
        // undefined?
        // first sequence
        if (prevdate == undefined) {
            final.push(new Array());
            final[currentseq].push(d);
        }
        else {
            // compare if difference to current date in loop is greater than a day
            var comp=new Date();
            comp.setDate(prevdate.getDate()+2);
            // Advance sequence if it is
            if (comp < d) {
                currentseq++;
                final[currentseq] = new Array();
            }
            // Push the date to current sequence
            final[currentseq].push(d);            
        }
        // store previous
        prevdate = d;
    });   

    return final;
}

Fiddle: 小提琴:

http://jsfiddle.net/f57Ah/1/ http://jsfiddle.net/f57Ah/1/

tried array sort with forEach 尝试使用forEach数组sort

var dates = [1367848800000, 1367935200000, 1368021600000,
           1368108000000, 1368194400000, 1368367200000,
           1368540000000, 1368626400000, 1368712800000];

var k = 0 , sorted = [[]];   

dates.sort( function ( a, b ){

    return +a > +b ? 1 : +a == +b ? 0: -1;
})
.forEach( function( v , i ){

    var a = v,b = dates[i+1]||0;

    sorted[k].push( +a );

    if ( (+b - +a) > 86400000) {
            sorted[++k] = []
    }
});

Later you can sort them per counts 之后您可以按计数对它们进行排序

sorted.sort( function ( a,b ){
    return a.length > b.length ? -1: 1;
});

The sorted array contains desired result jsfiddle sorted数组包含所需的结果jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM