如何找到一周中最多的一天?

时间:2018-05-29 09:36:58

标签: javascript arrays json

我有一系列日期,如何找到一周中最常见/第二/第三天等? 我试过以下

moment(@date field).week() 

但json日期数组怎么样?

2018-04-19
2018-04-19
2018-04-19
2018-04-20
2018-04-24
2018-05-02
2018-05-02
2018-05-02

2 个答案:

答案 0 :(得分:1)

有关详细信息,请参阅MapDate.prototype.getDay()Spread SyntaxArray.prototype.sort()Destructured AssignmentArray.prototype.map()



// Input.
const dates = ['2018-04-19','2018-04-19','2018-04-19','2018-04-20','2018-04-24','2018-05-02','2018-05-02','2018-05-02']
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

// Occurences.
const occurrences = dates => [...dates.reduce((m, date) => {
  const day = days[new Date(date).getDay()]
  m.set(day, (m.get(day) || 0) + 1)
  return m
}, new Map)].sort((A, B) => B[1] - A[1])

// Output
const output = occurrences(dates)

// Proof.
console.log('With Counts', output)
console.log('Without Counts', output.map(([day]) => day))




答案 1 :(得分:0)

  1. 获取一周的日子
  2. 按频率对其进行排序(删除重复项)
  3. 将它们翻译成工作日字符串(您也可以使用moment或Intl.DateTimeFormat执行此操作)
  4. 
    
    const dates = [
      '2018-04-19',
      '2018-04-19',
      '2018-04-19',
      '2018-04-20',
      '2018-04-24',
      '2018-05-02',
      '2018-05-02',
      '2018-05-02',
    ];
    
    const daysOfWeek = dates.map(date => new Date(date).getDay());
    
    // Now we have the days as numbers we can sort by frequency
    // This function is from a google search: https://stackoverflow.com/a/3579651/414062
    function sortByFrequency(array) {
      const frequency = {};
    
      array.forEach(value => frequency[value] = 0);
      const uniques = array.filter(value => ++frequency[value] == 1);
      return uniques.sort((a, b) => frequency[b] - frequency[a]);
    }
    
    const sortedDaysOfWeek = sortByFrequency(daysOfWeek);
    
    // Now translate to weekday values
    const weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    const weekdaysByFrequency = sortedDaysOfWeek.map(day => weekdays[day - 1]);
    
    console.log(weekdaysByFrequency);