2

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.

Christian Perry
  • 161
  • 1
  • 11

2 Answers2

4

You could take the indices of the wanted elements and use destructuring assignment.

var swap = (a1, a2, v1, v2) => {
        var i = a1.indexOf(v1),
            j = a2.indexOf(v2);

        [a1[i], a2[j]] = [a2[j], a1[i]];
    },
    array1 = ['Bob', 'Susan', 'Kevin', 'Jack', 'Tim'],
    array2 = ['George', 'Steve', 'Martha'];

swap(array1, array2, 'Jack', 'Martha')

console.log(array1);
console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

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