我有一个对象:
{
name: 'xxx',
date: '2016-01-01',
value: 'xxx'
},
{
name: 'xxx',
date: '2016-01-02',
value: 'xxx'
},
{
name: 'xxx',
date: '2016-01-01',
value: 'xxx'
},
{
name: 'xxx',
date: '2016-01-03',
value: 'xxx'
}
我想打印按周排序的值,每天只打印一个值,例如
This week:
- xxx from '2016.01.01'
- xxx from '2016.01.02'
- xxx from '2016.01.03'
Last week:
no values this week
等...
您是否知道如何正确实现这一目标?
我使用的是角度2和打字稿
答案 0 :(得分:0)
一步一步:
Item
(可选但简化后续步骤) getWeek()
功能(Chrome支持,但非正式) Map
Map
作为reduce()
电话的种子,按周和日期收集项目代码示例:(name
已被删除以简化代码)
type Item = { date: string; value: string; };
const items: Item[] = [{
date: '2016-01-01',
value: 'foo'
},
{
date: '2016-01-01',
value: 'foo2'
},
{
date: '2016-01-02',
value: 'bar'
},
{
date: '2016-02-01',
value: 'baz'
},
{
date: '2016-03-01',
value: 'lol'
}];
// Source: https://weeknumber.net/how-to/javascript
const getWeek = function (date: Date) {
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000
- 3 + (week1.getDay() + 6) % 7) / 7);
};
const itemsByWeek = items.reduce(
(map: Map<string, Map<string, Item[]>>, item: Item) => {
const [year, month, day] = item.date.split('-').map(x => +x);
const date = new Date(year, month, day);
const week = `${year}-${getWeek(date)}`;
let weekGroup = map.get(week);
if (!weekGroup) {
weekGroup = new Map([[item.date, [item]]]);
map.set(week, weekGroup);
} else {
const dayGroup = weekGroup.get(item.date);
if (!dayGroup) {
weekGroup.set(item.date, [item]);
} else {
dayGroup.push(item);
}
}
return map;
},
new Map<string, Map<string, Item[]>>());
const concertMapToKeyValueArray = <K, V>(map: Map<K, V>) => {
return Array.from(map.entries()).map(tuple => {
const [key, value] = tuple;
return { key, value };
});
};
concertMapToKeyValueArray(itemsByWeek)
.forEach(weekGroup => {
console.log(`Week: ${weekGroup.key}`);
concertMapToKeyValueArray(weekGroup.value)
.forEach(dayGroup => console.log(`- Date: ${dayGroup.key}, ` +
`Values: [${dayGroup.value.map(item => item.value).join(', ')}]`));
});
控制台中的输出:
Week: 2016-5
- Date: 2016-01-01, Values: [foo, foo2]
- Date: 2016-01-02, Values: [bar]
Week: 2016-9
- Date: 2016-02-01, Values: [baz]
Week: 2016-13
- Date: 2016-03-01, Values: [lol]