Is there a way to append elements from a pop operation into a different array?

I have developed a program that simulates team selection for kids playing various sports like football, baseball, and stickball. The program involves 10 kids stored in an array, each assigned a random power number. The goal is to sort through the array to identify the two kids with the highest powers, assign them to separate teams (teamOne and teamTwo), and determine which team gets to pick first based on a coin toss.

While the sorting and team allocation functions are working fine, I am facing challenges post coin toss. I would greatly appreciate any guidance or recommended resources to address this issue.

Below is the code snippet for reference. Thank you.


// function to generate a random number
let getRandNum = function (start, range) {
  let getRand = (Math.random() * range) + start;
  while (getRand > range) {
    getRand = (Math.random() * range) + start;
  };
  return getRand;
};

// array containing details of 10 kids
var Kids = [{
    name: "Bobby",
    random: getRandNum(1, 10)
  },
  {
    name: "Frankie",
    random: getRandNum(1, 10)
  },
  {
    name: "Juan",
    random: getRandNum(1, 10)
  },
  {
    name: "Sid",
    random: getRandNum(1, 10)
  },
  {
    name: "Ellie",
    random: getRandNum(1, 10)
  },
  {
    name: "Harry",
    random: getRandNum(1, 10)
  },
  {
    name: "Chester",
    random: getRandNum(1, 10)
  },
  {
    name: "Lucio",
    random: getRandNum(1, 10)
  },
  {
    name: "Nancy",
    random: getRandNum(1, 10)
  },
  {
    name: "Kim",
    random: getRandNum(1, 10)
  }
];

// function to sort the array based on random number
function compareValues(key, order = 'asc') {
  return function innerSort(a, b) {
    if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
      // property doesn't exist on either object
      return 0;
    }

    const varA = (typeof a[key] === 'string') ?
      a[key].toUpperCase() : a[key];
    const varB = (typeof b[key] === 'string') ?
      b[key].toUpperCase() : b[key];

    let comparison = 0;
    if (varA > varB) {
      comparison = 1;
    } else if (varA < varB) {
      comparison = -1;
    }
    return (
      (order === 'desc') ? (comparison * -1) : comparison
    );
  };
}

console.log(Kids.sort(compareValues('random', )));

const teamOne = Kids.pop();
const teamTwo = Kids.pop();

console.log(teamOne);
console.log(teamTwo);
console.log(Kids);

let coinToss = "Heads"

if (Math.floor((Math.random() * 2) + 1) == 2) {
  coinToss = "Tails";
};

console.log(coinToss);

if (coinToss = "Heads") {
  let x = 4;
  while (x > 0) {
    teamOne.push([Kids.pop()]);
    teamTwo.push([Kids.pop()]);
    x -= x;
  };
} else {
  let x = 4;
  while (x > 0) {
    teamTwo.push([Kids.pop()]);
    teamOne.push([Kids.pop()]);
    x -= x;
  };
  console.log("_____________");
  console.log(coinSide);
  console.log("_____________");
  console.log(teamOne.name);
  console.log("_____________");
  console.log(teamTwo.name);
};

Answer №1

The issue lies in not treating teamOne and teamTwo as arrays, preventing the use of "push". Additionally, the Kids array objects contain two values - "name" and "random" - so using "push" would add a new kid as an object.

To resolve this, first define teamOne and teamTwo as arrays instead of strings. Next, extract the "name" property from the Kids objects (assuming "random" was only used for sorting purposes). Lastly, assign a name to each team if they were defined as arrays.

Try something similar to this:

// function to generate a random number
let getRandNum = function (start, range) {
  let rand = (Math.random() * range) + start;
  while (rand > range) {
    rand = (Math.random() * range) + start;
  };
  return rand;
};

// array containing 10 kids with names and random numbers
var Kids = [{
    name: "Bobby",
    random: getRandNum(1, 10)
  },
  {
    name: "Frankie",
    random: getRandNum(1, 10)
  },
  // Add more kid objects here...
];

// sort the Kids array based on the random number

function compareValues(key, order = 'asc') {
  // Function code goes here...
}

console.log(Kids.sort(compareValues('random', )));

let teamOne = [];
let teamTwo = [];

// Assigned variables and populated teams with kid's names randomly

console.log(teamOne);
console.log(teamTwo);
console.log(Kids);

// Coin toss simulation for selecting team members alternatively

if (Math.floor((Math.random() * 2) + 1) == 2) {
  coinToss = "Tails";
};

for (let i = 0; i < 4; i++) {
    // Assigning team members based on coin toss result
};
// Displaying the results

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

What is the best way to generate an array from JSON data while ensuring that the values are not duplicated?

Upon receiving a JSON response from an API, the structure appears as follows: { "status": "success", "response": [ { "id": 1, "name": "SEA BUSES", "image": null }, { "id": 2, ...

Is it possible to submit a select menu without using a submit button within a loop?

I'm having an issue with my code that submits a form when an option in a select box is clicked. The problem arises when I try to put it inside a loop, as it stops working. Can anyone assist me with this? Below is the code snippet causing trouble: &l ...

Invoke the bootstrap js collapse() method within an Angular/Typescript environment

Currently, I am utilizing Bootstrap 3 alongside Angular 2 to collapse/hide content. However, I am facing an issue where I need the ability to collapse it when double-clicking on the button. Even though I created a function for this purpose, I seem to be un ...

Using JavaScript's AJAX to create conditional statements with the if-

Below is my JavaScript code that is meant to display a notification to the user if the PHP script below returns a MySQL select count result greater than 0: <script> $(document).ready(function() { function update() { ...

Facing a few hiccups in JavaScript or CSS code, but getting closer to making it work

Here is the code I currently have with HTML, CSS, and JavaScript. Everything is working correctly except for one small issue that I can't seem to resolve. I am new to JavaScript and believe that JavaScript is necessary to fix this problem. If not, the ...

Uncovering the JavaScript Linked to a Specific Element

Is there a way to link directly to the JavaScript controlling a particular HTML element, unlike the typical "inspect element" approach which is limited to HTML and CSS? ...

Cannot locate module using absolute paths in React Native with Typescript

I recently initiated a new project and am currently in the process of setting up an absolute path by referencing this informative article: https://medium.com/geekculture/making-life-easier-with-... Despite closely following the steps outlined, I'm en ...

Display an image according to the text input

I am working on a static page where I need to showcase the percentage of a project spent on different practices. Is it possible to set a background image in the li element based on the value displayed? I believe javascript could provide a solution for this ...

Despite the page loading properly, Cypress is struggling to retrieve the URL value after the target attribute has been removed

In order to verify that a link leads to the correct page, I want Cypress to click on the link and check if the URL contains a specific string. To achieve this, I have created the following function: checkLink = (linkEl, expectedPath) => { let pathS ...

The main server is not yielding any results from the MongoDB query

I attempted to utilize promises in order to retrieve all the items from my mongoDB database. Here is the code I used: exports.findAll = function(){ return new Promise(function(resolve, reject){ Collection.find({}, function(err, res){ if(err ...

Hide dropdown when clicked outside of it

Can someone help me modify my JavaScript code so that when I click on a new dropdown, it closes the previous one and keeps only the current one open? function manageDropdowns() { var dropdowns = document.querySelectorAll('.dropdown:not(.is-hove ...

Issue encountered with the style parameter in print-js when attempting to print from a Vue.js component

While browsing the print-js documentation, I came across a feature that allows us to pass style as a string to the printJS function. However, when attempting to apply this style, I encountered an error preventing the print action: The error I'm facin ...

Exploring the process of adding arrays to highcharts using jQuery

All my coding work has been carried out on FIDDLE I have carefully monitored all the arrays: MARKET[0], MARKET[1], MARKET[2], MARKET[3], MARKET[4], MARKET[5], MARKET[6], MARKET[7]. They display correctly in alerts. However, when I attempted to incorporate ...

Tips for triggering animations on nested content when the parent slide is animated and enters the viewport without relying on traditional scrolling methods

I would like to implement a JavaScript solution that will animate the content of a nested DIV within a parent slide when the parent slide comes into view. Currently, the content in the nested DIV only animates when a scroll command is triggered after the ...

Incorporating the use of preventDefault() and stopPropagation() methods

I am a beginner in coding, particularly with javascript. I attempted to create a flip div effect but encountered an issue where clicking one .button would trigger the flip effect on all similar divs on the page. I have tried using .preventDefault() and .st ...

UI Select not found result event

Currently implementing https://github.com/angular-ui/ui-select and looking for a solution to trigger an event (such as opening a modal) when no results are found while using a filter. <ui-select ng-model="SelectedCustomer.selected" theme="select2"> ...

Altering the background image of the body in Angular by utilizing $rootScope

I need to customize the background image based on specific routes in my application. However, I am facing an issue with the rootScope not updating the value as expected. I have set the value to true in the controller for the route that requires a different ...

Looking to implement a star rating feature in Vue.js 2?

My perspective is as follows : <div class="col-md-8"> ... <star-rating :value="3"></star-rating> ... </div> This is how my star-rating component looks like : <template> <span class="rating"> &l ...

What is the best way to receive the return value of a function when validating a form?

I am currently working on a website and need to validate a form to ensure that no field is left empty. If any field is empty, I want to display a message stating "This field is empty" next to the field name. Here is my form code: <form action ...

Can you explain the process of utilizing Angular databinding to display nested information?

I'm facing a challenge with databinding when working with nested arrays in multiple timeslots and windows. Despite understanding the basics, I can't seem to make it work no matter how I try different approaches. It's really frustrating not k ...