1

I have two arrays that look like this:

const players = ["id1", "id2", "id3", "id4"]
const games = ["gid1", "gid2"]

I need to return an array that looks like this:

const newArray = [
  {playerId: "id1", gameId: "gid1"}, {playerId: "id1", gameId: "gid2"},
  {playerId: "id2", gameId: "gid1"}, {playerId: "id2", gameId: "gid2"},
  {playerId: "id3", gameId: "gid1"}, {playerId: "id3", gameId: "gid2"},
  {playerId: "id4", gameId: "gid1"}, {playerId: "id4", gameId: "gid2"}
]

What's the best way to achieve this? I have been trying a combination of map and reduce, but can't seem to figure it out.

2
  • @charlietfl: Looks like a cartesian product. But would be good if it said. Commented Nov 26, 2017 at 19:12
  • 2
    "I have been trying a combination of map and reduce, but can't seem to figure it out." Show us that. Separately: Why reach for something complicated when nested loops will do the job nicely? Commented Nov 26, 2017 at 19:13

4 Answers 4

3

With Array.reduce() and Array.forEach() functions:

const players = ["id1", "id2", "id3", "id4"]
const games = ["gid1", "gid2"]

const result = players.reduce((r, p_id) => {
    games.forEach((g_id) => r.push({playerId: p_id, gameId: g_id}));
    return r;
}, []);

console.log(result);

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

Comments

3

You want to create cartesian array. You can perform it like this;

var newArray = [];
for (var i = 0; i < players.length; i++) {
    for (var l = 0; l < games.length; l++) {
        var merged = {playerId: players[i], gameId: games[l]};
        newArray.push(merged);
    }
}

Comments

1

Here's a solution using es6 for...of

const players = ['id1', 'id2', 'id3', 'id4']
const games = ['gid1', 'gid2']
let newArray = []

for (let game of games) {
   for (let player of players) {
       newArray.push({playerId: player, gameId: game})
       }
    }

Comments

0

Here's a different take on the functional approach which breaks down the code into smaller parts:

const players = ["id1", "id2", "id3", "id4"]
const games = ["gid1", "gid2"];

const flatten = arrs => [].concat(...arrs);
const getGame = (id, gid) => ({ playerId: id, gameId: gid });
const getGames = games => id => games.map(gid => getGame(id, gid));
const output = flatten(players.map(getGames(games)));

console.log(output)

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.