【问题标题】:How do I group items in an array by date?如何按日期对数组中的项目进行分组?
【发布时间】:2017-10-18 03:44:39
【问题描述】:

给定以下对象数组:

[
{
"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]);
        }

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

任何帮助或指导将不胜感激。

【问题讨论】:

  • 到目前为止您尝试过什么?这里的解决方案很简单。
  • 嗨 Spencer,我不确定如何在 cmets 中发布代码,但我创建了一个空数组,并运行了一个 for 循环来迭代第一个信息。我将原始日期切片以获取 (yyyy-mm-dd) 中的格式,然后创建另一个 for 循环以检查该日期是否存在于当前空数组中,如果不存在,我将为此创建一个新键日期,然后将任何游戏传入游戏密钥。一开始我遇到了一个无限循环,我的内存崩溃了,然后我一直覆盖我以前的对象。
  • 您不想在 cmets 中发布您的代码,而是将其添加为问题的编辑。
  • 您的意思是要将键设置为日期,不包括时间吗?所以会有2017-10-142017-10-04 作为键?
  • 嗨斯宾塞,我更新了我的帖子以显示我所做的......我得到了与发布的另一个答案类似的结果,但我想要做的是获取一个带有对象的数组对于每个日期,它都有自己的密钥,以及玩游戏的另一个密钥。所以 [{date: 'date string', games: [array of games]}]

标签: javascript arrays for-loop iteration grouping


【解决方案1】:

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

更新添加数组格式版本

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);

【讨论】:

  • 嗨,奥斯汀,感谢您的回答。我能够使用 for 循环得到类似的答案,但我需要将日期作为它自己的键,并将游戏作为另一个键的值列在数组中(都在同一个对象中) .所以 {date: 'date', games: [...]}
  • @Blake 明白了,只是看到了不同的格式。我认为我刚刚添加的更新应该可以满足您的需求。
  • 非常感谢Austin的帮助,这个问题一直让我头疼一整天!
  • 天哪,我还以为这个问题要花我好几天的时间,哈哈,首先在谷歌上搜索,第一个链接,你的帖子,非常感谢!太完美了!!!
【解决方案2】:

    let a =[{
      "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,
      }]

      let finalObj = {}
      a.forEach((games) => {
        const date = games.time.split('T')[0]
        if (finalObj[date]) {
          finalObj[date].push(games);
        } else {
          finalObj[date] = [games];
        }
      })
      console.log(finalObj)

【讨论】:

  • 这很简单,也很棒。节省了一天。谢谢。
【解决方案3】:

这就是你要找的吗???

var 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
    }
];

function extract() {
    var groups = {};

    data.forEach(function(val) {
        var date = val.time.split('T')[0];
        if (date in groups) {
            groups[date].push(val.sport);
        } else {
            groups[date] = new Array(val.sport);
        }
    });

    console.log(groups);
    return groups;
}

extract();

【讨论】:

  • 嗨,Bobby,感谢您抽出宝贵时间回答我。我已经得到了类似的格式。我需要的格式(奥斯汀在上面回答正确)是:[{date:'date string', games:[array of games for this date]}]。
  • 哦,我明白了;D Happy Coding!
【解决方案4】:

使用 RxJS, 就我而言,使用 Angular

import { of } from "rxjs";
import { groupBy, map, mergeMap, reduce, toArray } from "rxjs/internal/operators";

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,
  }
];

of(...data).pipe(
  groupBy((p: any) => p.time.split('T')[0]),
  mergeMap(group$ =>
    group$.pipe(reduce((acc, cur) => [...acc, cur], [`${group$.key}`]))
  ),
  map(arr => ({ date: arr[0], games: arr.slice(1) })),
  toArray()
).subscribe(p => console.log(p));

结果:

【讨论】:

  • 甜!!谢谢你
猜你喜欢
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 2017-10-29
  • 2020-03-28
  • 1970-01-01
相关资源
最近更新 更多