Search code examples
javascriptarraysnested-loopsreduce

I want to separate my array into other arrays by matchday


I'm trying to separate a huge array in order of matchday. There are 38 matchdays in total, I'm trying to display the games by matchdays.

I have this

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

I would like something like this

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

So you can see I create a new array for each different matchday, those new arrays will be nested inside the main array.

My poor attempt:

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

    }

Solution

  • You can use a reducer for that. Reduce to object with matchdays keys, and retrieve its values. Something like:

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