0

newbie here. I have a set of arrays. My target is to join 1 data to another data if they have the same values. For example, player 1 = level 1, and player 6 = level 1, therefore they'll be joined on the same array and inserted to the database. As far as I know, I think it has to do with for-each. How can I make it work? Thank you in advance.

enter image description here

const players = [
    {
        id: 1,
        name: 'player1',
        level: '1',
    
    },
    {
        id: 2,
        name: 'player2',
        level: '2',
     
    },
    {
        id: 3,
        name: 'player3',
        level: '3',
  
    },
    {
        id: 4,
        name: 'player4',
        level: '3',
      
    },
    {
        id: 5,
        name: 'player5',
        level: '2',
     
    },
    {
        id: 6,
        name: 'player6',
        level: '1',
     
    }
];
Manish Kumar
  • 162
  • 3
Dark
  • 132
  • 1
  • 15
  • 1
    You can [group by the `level` key](https://stackoverflow.com/questions/40774697/how-to-group-an-array-of-objects-by-key) – VLAZ Jun 16 '21 at 09:00

1 Answers1

1

You could make a helper function to filter your array for specific levels:

const filterByLevel = (players, level) => players.filter(player => player.level === level);

// create new array only containing players with the given level
const levelTwoPlayers = filterByLevel(players, '2');

console.log(JSON.stringify(levelTwoPlayers));
// output: [{"id":2,"name":"player2","level":"2"},{"id":5,"name":"player5","level":"2"}]

Hope this helps - have fun coding

Apfelbox
  • 367
  • 4
  • 13