我想在比赛日之前将我的数组分成其他数组

I want to separate my array into other arrays by matchday

我正在尝试按照 比赛日 的顺序分离一个巨大的数组。总共有 38 个比赛日,我正在尝试按比赛日显示比赛。

我有这个

 data.matches = [{matchday: 1, team: xxx}, {matchday: 1, team: xxx}, {matchday: 2, team: xxx} etc..]

我想要这样的东西

  data.matches = [[{matchday: 1, team: xxx}, {matchday: 1, team: xxx} ],[{matchday: 2, team: xxx}] etc..]

所以你可以看到我为每个 不同的 比赛日创建了一个新数组,这些新数组将嵌套在主数组中。

我的失败尝试:

let results: any = [];

    if (isSuccess) {
        data.matches.map((item: any) => {
            for (let i = 1; i < 38; i++) {
                if (item.matchday === i) {
                    results.push(item);
                } else {
                    results.splice(i, 0, item);
                }
            }
        });
        console.log(results);

    }

你可以使用这个方法:

const matches = [{matchday: 1, team: "xxx"}, {matchday: 1, team: "xxx"}, {matchday: 2, team: "xxx"}]
const result = Array.from(matches
        .reduce((m, val) => m.set(val.matchday, [...(m.get(val.matchday) || []), val]), new Map)
        .values()
);
console.log(result)

您可以为此使用 reducer。使用 matchdays 键还原为对象,并检索其值。类似于:

const matches = [
  {matchday: 1, team: `yxx`}, 
  {matchday: 1, team: `xyx`}, 
  {matchday: 2, team: `xxy`},
  {matchday: 15, team: `yyx`},
  {matchday: 15, team: `yyy`} ];
const byDay = Object.values(
  matches.reduce( (acc, res) => {
    acc[`day${res.matchday}`] = acc[`day${res.matchday}`] 
      ? acc[`day${res.matchday}`].concat(res) : [res];
    return acc;}, {} )
  );
console.log(byDay);
.as-console-wrapper {
    max-height: 100% !important;
}