我有一系列日期,如何找到一周中最常见/第二/第三天等? 我试过以下
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
答案 0 :(得分:1)
有关详细信息,请参阅Map
,Date.prototype.getDay()
,Spread Syntax
,Array.prototype.sort()
,Destructured Assignment
和Array.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)
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);