Array Of JS Dates How To Group By Days

前端 未结 4 1469
旧时难觅i
旧时难觅i 2020-12-05 18:10

I\'m trying to figure out the most optimal and with as minimum amount of loops way to group my array of js dates objects from this: (Take a note this is browser console outp

4条回答
  •  鱼传尺愫
    2020-12-05 18:21

    Presuming your data is actually strings, I don't know why you think you need either of those libraries. You are just grouping strings based on substrings.

    ES5 introduced reduce, which is great for accumulating things:

    A helper to create an array of dates:

    // Generate a dates array given a start date and how many to create:
    function genDates(startDate, count) {
      var d = new Date(+startDate),
          dates = [d];
      for (var i=0; i

    This answer originally dealt with strings, modified to work with Dates:

    // Generate date key 'MMM dd'
    // Replaces use of moment.js
    function getDateKey(date) {
      var d = date.getDate();
      var m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
      return m[date.getMonth()] + ' ' + ((d<10?'0':'') + d);
    }
    
    // Generate an array in format [{day:'MMM dd', times:[d0, d1, ...]}, ...]
    // Replaces use of underscore.js
    var obj = dates.reduce(function(acc, d) {
                var p = getDateKey(d)
                if (!acc[0].hasOwnProperty(p)) acc[0][p] = [];
                acc[0][p].push(d);
                return acc;
              },[{}])
              .reduce(function(acc, v){
                Object.keys(v).forEach(function(k){acc.push({day:k, times:v[k]})});
                return acc;
              },[]);
    
    console.log(JSON.stringify(obj));
    

    If optimal performance is the key, the above is 20 times faster than the underscore + Moment solution for an array of 5 to 100 dates. To make it faster, remove all use of iterators and libraries and use a single function with for loops. Note that the above is only one line of code longer than the solution using Moment.js and underscore.js.

提交回复
热议问题