Swap two pairs of elements in an array in a random order

I have a list of team members and also 2 substitute players: team = Samson, Max, Rowan, Flynn, Jack subs = Struan, Harry

I am facing a challenge in randomly swapping the 2 subs into the team. The difficulty lies in ensuring that only these 2 elements are swapped and that both are included in the swap. Initially, I attempted to loop through the subs array and swap each element randomly with an element from the team array. However, this method often resulted in scenarios where Struan was swapped with Max and then Harry was swapped with Struan, leaving Struan still in the subs array instead of being transferred to the team.

Therefore, my objective is to specifically exchange the 2 elements in the sub array with random elements from the team array. How can I accomplish this?

Answer №1

To achieve this functionality, utilize the following function. Input the current team and substitutes to receive a new team with random substitutions.

const players = ['Aiden', 'Ella', 'Liam', 'Mia', 'Olivia']
const subs = ['Ethan', 'Sophia']

const substitutePlayers = (players, subs) => {
  const newTeam = [...players]
  
  function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max-1);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  
  let num1 = getRandomInt(0, players.length)
  let num2 = getRandomInt(0, players.length)
  
  while(num2 === num1) num2++
  
  newTeam[num1] = subs[0]
  newTeam[num2] = subs[1]
  
  return newTeam
}

const updatedTeam = substitutePlayers(players, subs);

console.log(updatedTeam)

Answer №2

Here's a possible solution:

function chooseRandomItem () {
   let randomItem = team[Math.floor(Math.random()*team.length)];
   if(subs.indexOf(randomItem) < 0){
      return randomItem;
   } else {
      return chooseRandomItem();
   }
}

subs.forEach((item, index) => {
   subs.splice(index, 1, chooseRandomItem());
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

AJAX does not execute all inline JavaScript code

I am currently using AJAX to load a fragment of a document. I have successfully loaded 'external' scripts, but I am encountering issues when trying to execute all the JavaScript within <script> tags. Below is an example of the HTML fragmen ...

Needing to utilize the provide() function individually for every service in RC4

In Beta, my bootstrapping code was running smoothly as shown below: bootstrap(App, [ provide(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, helperService: HelperService, authProvider: AuthProvider) => new CustomHt ...

What is the best way to retrieve data attributes from multiple div elements that share the same class name?

I have multiple div elements with the same class name. I want to extract the data attribute from these div's. I have tried some code and managed to get the result. However, I am unsure if this is the best approach for retrieving data("cartid"). Any as ...

How to emphasize a portion of an expression in AngularJS using bold formatting

I have a specific goal in mind: to emphasize part of an angular expression by making it bold. To achieve this, I am working with an object obj which needs to be converted into a string str. obj = $scope.gridOptions1.api.getFilterModel(); for (var pr ...

Unable to transfer files, encountering issues with PHP and AngularJS integration

I am currently working on uploading files using both AngularJS and PHP. For the AngularJS part, I am utilizing angular-file-upload from https://github.com/danialfarid/angular-file-upload. I suspect that the issue lies in my PHP code, as it fails to move ...

When attempting to utilize nsIPrefBranch in a Firefox extension to save data, an unexpected error of NS_ERROR_UNEXPECTED occurs

I am facing a challenge with saving persistent data in a Firefox extension. Currently, I am attempting to utilize nsIPrefBranch in the following manner: var db = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.ns ...

Steps to clear the form in vue after the ajax request has been successfully submitted

Exploring Vue.js Web Form Validation with a Scenario If you are interested in the vue-form validator library, it can be found at https://github.com/fergaldoyle/vue-form For a demonstration of this scenario, check out the following jsfiddle link: https:/ ...

Using jQuery to Activate Genuine Events

Is it true that jQuery's trigger() only executes event handlers bound with jQuery? I have some modules that utilize native browser event binding. Although the solution from works for me, I'm curious if there is a built-in way in jQuery to handle ...

The smooth scroll feature is not functioning properly on the animated mouse-scroll down button

I've recently added an Animated Mouse Scroll Down button on my website. However, when I click the button, the smooth scroll feature is not working as expected. Important Note: I already have a separate button for navigating to the next section where ...

Issue with pop-up functionality on web page using HTML, CSS, and JavaScript

Recently, I created a unique popup using HTML. You can see the complete code (excluding CSS) here: https://codepen.io/nope99675/pen/BawrdBX. Below is the snippet of the HTML: <!DOCTYPE html> <html> <head> <meta charset=&quo ...

Encountering the issue of "Cannot read properties of undefined" while attempting to pass data to a prop

Currently, I am developing a Vue application that heavily relies on charts. The issue lies in the fact that I am fetching data from the database individually for each chart component, resulting in multiple calls and a slower page load time. I am looking to ...

Transferring data from jQuery Ajax to PHP

I'm facing a challenge in retrieving a value back to PHP that I can manipulate and save to the database. It appears that using the GET method with jQuery AJAX is not yielding the desired results. Below is the PHP code snippet where I attempt to captur ...

The Node.js application encounters a blank response when making a GET request to the API

As a newcomer to node.js, I'm attempting to describe the issue at hand as clearly as possible. If clarification is needed, please let me know. In my current node.js project, I am faced with a challenge where I need to take a code received from the re ...

Use setTimeout and setInterval with the initial input without parentheses or double quotation marks

<!DOCTYPE HTML> <html> <head> <script type="text/javascript"> var count=0; function increaseCount(){ document.getElementById('txt').value=count; count++; setTimeout(increaseCount(),1000); } </script> </head&g ...

Trouble with event.preventDefault functionality

This snippet of code I'm working on is pretty basic, nothing too intricate. $("input#send").submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: add.php, data: data, succe ...

Steps for importing jQuery typings into TypeScript:1. First, install the jQuery

I've searched for similar questions, but haven't found one that matches my issue. Can someone help me figure out what to do next? In my Visual Studio project, I used package.json to download jquery typings into the node_modules folder: { "ver ...

What impact does the depth of an array have on performance in PHP?

While there are similar questions on this topic, the arrays I have are quite unique. First array structure : array( [0] => array( 'stat1' => 50, 'stat2' => 12, 'stat3' => 0, &a ...

Techniques for adding values to arrays in JavaScript

My Anticipated Result let Album = { album_desc: AlbumTitle, id: 1, album_title: 'ss', AlbumDescription: 'sdsd', ImageName: 'image.jpg', album_pics: below array }; I am looking to dynamically p ...

Is the NodeJS debugger prone to crashing when utilizing `this` to invoke an unidentified function?

My JavaScript file contains the code below: (function (context) { console.log(123); debugger; })(this); When I run my script in debug mode like this: $ node debug script.js I noticed that the other lines in debug mode are not colored green. Wha ...