0

I have following array result:

Example:

[
    {
         id: "1",
         league: {
              name: "World Club Friendlies",
              team: "Simple 1 & Simple 2"
          }
    },
    {
         id: "2",
         league: {
              name: "Senegal Ligue 2",
              team: "Simple"
          }
    },
    {
         id: "3",
         league: {
              name: "World Club Friendlies",
              team: "Simple 3 & Simple 4"
          }
    },
]

The First and Third league names are similar.

The above code output looks like this:

League Name: World Club Friendlies / Team: Simple 1 & Simple 2

League Name: Senegal Ligue 2 / Team: Simple

League Name: World Club Friendlies / Team: Simple 3 & Simple 4

Now i need to print following result:

League Name: World Club Friendlies / Team: Simple 1 & Simple 2 & Simple 3 & Simple 4

League Name: Senegal Ligue 2 / Team: Simple

I have somthing like this code:

foreach($content as $result){
   echo $result['league']['name'];
   echo $result['team'];
}
1
  • No any Body ? ............ Commented Dec 31, 2019 at 1:31

1 Answer 1

0

Use reduce and check for team name as key and apply the condition that you want as follows:

var data = [{
    id: "1",
    league: {
      name: "World Club Friendlies",
      team: "Simple 1 & Simple 2"
    }
  },
  {
    id: "2",
    league: {
      name: "Senegal Ligue 2",
      team: "Simple"
    }
  },
  {
    id: "3",
    league: {
      name: "World Club Friendlies",
      team: "Simple 3 & Simple 4"
    }
  },
]

var res = data.reduce((acc, curr) => {
  if (acc[curr.league.name]) {
    acc[curr.league.name] = {
      name: curr.league.name,
      team: acc[curr.league.name].team + " & " + curr.league.team
    }
  } else {
    acc[curr.league.name] = {
      name: curr.league.name,
      team: curr.league.team
    }
  }
  return acc;
}, {});
for (data in res) {
  console.log("League name: " + res[data].name + "/Team:" + res[data].team)
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.