gpt4 book ai didi

javascript - 如何按日期对数组中的项目进行分组?

转载 作者:搜寻专家 更新时间:2023-11-01 04:44:40 25 4
gpt4 key购买 nike

给定以下对象数组:

[
{
"notes": "Game was played",
"time": "2017-10-04T20:24:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "10",
"game_id": 1,
},
{
"notes": "Game was played",
"time": "2017-10-04T12:35:30+00:00",
"sport": "lacrosse",
"owner": "steve",
"players": "6",
"game_id": 2,
},
{
"notes": "Game was played",
"time": "2017-10-14T20:32:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "4",
"game_id": 3,
},
{
"notes": "Game was played",
"time": "2017-10-04T10:12:30+00:00",
"sport": "hockey",
"owner": "henry",
"players": "10",
"game_id": 4,
},
{
"notes": "Game was played",
"time": "2017-10-14T20:34:30+00:00",
"sport": "soccer",
"owner": "john",
"players": "12",
"game_id": 5,
}
]

我正在尝试创建一个新数组,它将创建一个对象,其中每个日期(作为键)以及在同一对象中的游戏(另一个键)下列出的该日期玩的所有游戏。

新数组应该是这样的:

[
{
date:'date string',
games:[array of games played on the date]
},
{
date: 'other date',
games:[games under the other date]
}
]...

这是我所做的:

let t = this.state.data; (data above)
let list = [];
for (let i = 0; i < t.length; i++) {
let dates = t[i].time.slice(0,10);

if (!list[dates]) {
list[dates] = [];
}
list[dates].push(t[i]);
}

我的版本返回一个以日期为值的数组,然后在其中列出游戏,但我试图将它们列在同一个对象中作为不同的键。

如有任何帮助或指导,我们将不胜感激。

最佳答案

这是一个使用reduce 的解决方案。将时间拆分为日期字符串,然后为每个日期设置一个key。如果 key 存在,将其推送到数组中:

更新增加数组格式版本

const data = [
{notes: 'Game was played', time: '2017-10-04T20:24:30+00:00', sport: 'hockey', owner: 'steve', players: '10', game_id: 1},
{ notes: 'Game was played', time: '2017-10-04T12:35:30+00:00', sport: 'lacrosse', owner: 'steve', players: '6', game_id: 2 },
{ notes: 'Game was played', time: '2017-10-14T20:32:30+00:00', sport: 'hockey', owner: 'steve', players: '4', game_id: 3 },
{ notes: 'Game was played', time: '2017-10-04T10:12:30+00:00', sport: 'hockey', owner: 'henry', players: '10', game_id: 4 },
{ notes: 'Game was played', time: '2017-10-14T20:34:30+00:00', sport: 'soccer', owner: 'john', players: '12', game_id: 5 }
];

// this gives an object with dates as keys
const groups = data.reduce((groups, game) => {
const date = game.time.split('T')[0];
if (!groups[date]) {
groups[date] = [];
}
groups[date].push(game);
return groups;
}, {});

// Edit: to add it in the array format instead
const groupArrays = Object.keys(groups).map((date) => {
return {
date,
games: groups[date]
};
});

console.log(groupArrays);

关于javascript - 如何按日期对数组中的项目进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46802448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com