Search code examples
javascriptarraysoopobjectprototype

Elegant way to swap items from one array to another in JavaScript?


Is there an elegant way to swap items from one array to another using vanilla JS?

This functionality would work if you're building a simple app for sports teams. On a given team, when you swap a player out from the starting lineup (array1), you replace them with a player from the substitute lineup (array2).

Once the selections are made, the arrays are updated, with the selected array item from array 2 now appearing in array 1, and vice-versa.

Pseudocode Example:
Starting Lineup = Bob, Susan, Kevin, Jack, Tim
Substitude Lineup = George, Steve, Martha

Player to sub out: Jack
Player to sub in: Martha

// JS Magic Activates! (Insert your ingenious code here.)

Result:
Starting Lineup: Bob, Susan, Kevin, Martha, Tim
Substitute Lineup: George, Steve, Jack

I found an elegant solution to swap the order of two items in a single array, using a prototype method. However, this won't work if you're dealing with two items in two different arrays.

My question is less about whether a solution is possible (which of course it is), but what the best way to do this is, using clean, precise, and elegant code, without the need for a bunch of for-loop spaghetti.


Solution

  • Not glamourous, and maybe missing your sentiment - but in two lines you can do it

    var Starting_Lineup = ["Bob", "Susan", "Kevin", "Jack", "Tim"];
    var Substitute_Lineup = ["George", "Steve", "Martha"];
    
    /*
    Player to sub out: Jack
    Player to sub in: Martha
    */
    
    // JS Magic Activates! (Insert your ingenious code here.)
    Starting_Lineup[Starting_Lineup.indexOf("Jack")]="Martha";
    Substitute_Lineup[Substitute_Lineup.indexOf("Martha")]="Jack";
    
    
    /*
    Result: 
    Starting Lineup: Bob, Susan, Kevin, Martha, Tim
    Substitute Lineup: George, Steve, Jack
    */

    If you want a function:

    var Starting_Lineup = ["Bob", "Susan", "Kevin", "Jack", "Tim"];
    var Substitute_Lineup = ["George", "Steve", "Martha"];
    
    /*
    Player to sub out: Jack
    Player to sub in: Martha
    */
    
    [Starting_Lineup,Substitute_Lineup]=swap_player(Starting_Lineup,Substitute_Lineup,"Jack","Martha");
    
    function swap_player(team_1,team_2,player_1,player_2){
      team_1[team_1.indexOf(player_1)]=player_2;
      team_2[team_2.indexOf(player_2)]=player_1;
      return [team_1,team_2];
    }