我有objs清单:
[{
name: one,
date: 2017-09-18
}, {
name: two,
date: 2017-09-11
}, {
name: three,
date: 2017-09-13
}]
我想按周排序。
可能像:
{
1week(or , maybe better key like start of week): [{
name: two,
date: 2017-09-11
}, {
name: three,
date: 2017-09-13
],
2week: [{
name: one,
date: 2017-09-18
}]
}
如何确定日期属于哪一周?
我该如何做得更好?
最佳答案
我玩了这个,我认为这类似于您所需要的:
https://jsfiddle.net/pegla/ytmayemr/
码:
let arrayOfDates = [{
name: 'one',
date: '2017-09-18'
}, {
name: 'two',
date: '2017-09-11'
}, {
name: 'three',
date: '2017-09-13'
}];
function getWeekNumber(d) {
// Copy date so don't modify original
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
// Get first day of year
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
// Return array of year and week number
return [d.getUTCFullYear(), weekNo];
}
let newArrayOfDatesByWeek = arrayOfDates.reduce((prevVal, currVal, index)=>{
let week = `week ${getWeekNumber(new Date(currVal.date))[1]} of ${getWeekNumber(new Date(currVal.date))[0]}`;
if(!(week in prevVal)) {
prevVal[week] = [];
}
prevVal[week].push(currVal);
return prevVal;
}, []);
console.log(newArrayOfDatesByWeek);
getWeekNumber函数由RobG从此答案中获取,因此感谢您:
Get week of year in JavaScript like in PHP
关于javascript - AngularJS 1:按周排序日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46282497/