Separate players into two teams based on their ratings using AngularJS / JavaScript

In my possession are an array of players along with their names and ratings.

$scope.players = [
  {"name": "Qasim", "rating": "10"}, 
  {"name": "Mahsam", "rating": 10}, 
  {"name": "Aj", "rating": 3}, 
  {"name": "Osman", "rating": 7}, 
  {"name": "Usama", "rating": 7}, 
  {"name": "Bilal", "rating": 3}
]

The task at hand is to categorize players into two teams based on their ratings.

var playerLength = $scope.players.length,
grouped = _.groupBy($scope.players,function(item){return item.rating});

The objective is to form two balanced teams with equal ratings.

Answer №1

If you're looking for a strategy to allocate players to teams, this solution might be of interest. The approach involves iterating through all the players and assigning each player to the team with the lowest overall strength.

For a more visual representation and better understanding, check out this JSFiddle demonstration.

const myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.players = [{
    "name": "Sarah",
    "rating": 9
  }, {
    "name": "John",
    "rating": 8
  }, {
    "name": "Emily",
    "rating": 4
  }, {
    "name": "Mike",
    "rating": 6
  }, {
    "name": "Laura",
    "rating": 5
  }, {
    "name": "Chris",
    "rating": 3
  }];

  $scope.team1 = [];
  $scope.team2 = [];

  $scope.createTeams = function() {
    angular.forEach($scope.players, function(player) {
      if ($scope.teamStrength($scope.team1) < $scope.teamStrength($scope.team2)) {
        $scope.team1.push(player);
      } else {
        $scope.team2.push(player);
      }
    });
  }

  $scope.teamStrength = function(team) {
    let total = 0;
    if (team.length === 0) return 0;
    for(let i = 0; i < team.length; i++) {
      total += team[i].rating;
    }
    return total;
  };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <button ng-click="createTeams()">Create Teams!</button>
    
    <h1>Team 1</h1>
    <div ng-repeat="p in team1">
      {{p.name}} ({{p.rating}})
    </div>
    
    <h1>Team 2</h1>
      <div ng-repeat="p in team2">
    {{p.name}} ({{p.rating}})
    </div>
  </div>
</div>

Answer №2

let playersMap = {};
let ratingArr = [];
let teamA = [];
let teamB = [];

for(let id in $scope.players){
    playersMap[$scope.players[id].rating] = $scope.players[id];
    ratingArr.push($scope.players[id].rating);
}
ratingArr.sort();
for(let i = 0; i < ratingArr.length; i+=2) {
    teamA.push({name: playersMap[ratingArr[i]].name, rating: playersMap[ratingArr[i]].rating});
}
for(let i = 1; i < ratingArr.length; i+=2){ 
    teamB.push({name: playersMap[ratingArr[i]].name, rating: playersMap[ratingArr[i]].rating});
}

Answer №3

One possible approach:

Note: Adjustments have been made to align with the query.

var soccerPlayers = [
  {"name": "David", "rating": "10"}, 
  {"name": "Luis", "rating": 10}, 
  {"name": "John", "rating": 3}, 
  {"name": "Roberto", "rating": 7}, 
  {"name": "Carlos", "rating": 7}, 
  {"name": "Michael", "rating": 3}
];

soccerPlayers.sort(function(a, b){
    return a.rating - b.rating
});

console.log(soccerPlayers); //sorted

var teamA = [], teamB = [];

//In this scenario, each player has the same rating twice
for (let index=0;index<soccerPlayers.length;index += 2) {
    teamA.push(soccerPlayers[index]);
    teamB.push(soccerPlayers[index+1]);
}
console.log(teamA, teamB);

:)

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

Processing data from a Buffer object using the .map() method and sending it as props to a component

As I work on my application, I encounter a challenge when dealing with a Buffer object that contains data from a file. My intention is to render the component Bar for each byte in this buffer and pass the byte as a prop. However, I am facing an issue with ...

Tips for recognizing hyperlinks within a block of text and converting them to clickable links in Angular 2

My task is to create clickable links within a paragraph of strings. I tried using a custom pipe, but seem to be missing something essential. Here's my attempt: import { Pipe, PipeTransform } from '@angular/core'; import { DecimalPipe ...

Switch up color scheme on table with checkbox activation

I'm currently using the AdminLTE template (Bootstrap) and I'd like to modify the color of the table row when my checkbox is checked. <table id="example1" class="table table-bordered table-striped dataTable" aria-describedby="example1_info"> ...

Switch out "FOR" in order to sum up every value within an array

Utilizing Javascript, I have an array defined as follows: counts: [ { id: 1, value: 0 }, { id: 2, value: 10 }, { id: 3, value: 5 }, { id: 4, value: 3 } ] I aim to calculate a variable named total that holds the sum of all valu ...

Is it more advantageous in Vue to pre-process and save data directly to the data property, or to utilize computed properties?

I am interested in hearing diverse perspectives on this topic. When working with Vue (and possibly other frameworks), is it more beneficial to prepare non-reactive data through a method and store it in the data for use in the template, or is it preferable ...

The ng command in my AngularJS project is not being recognized, however, running npm run ng

One key point to note is that this project is built on AngularJS, not Angular. I am unable to install @angular/cli due to certain restrictions. So far, I have successfully set up node v8.11.3 (along with NPM v6.7.0) and installed AngularJS framework. To g ...

The React Router path is inaccurately matching to a different route

I'm currently utilizing React version 4.2 for my application, but it appears to be having trouble matching the correct paths for the routes. <Provider store={store}> <BrowserRouter> <div> <Switch> ...

Euler 13: Surprising outcome when attempting to combine several String variables

I'm currently working on a challenging problem found on euler: here Large sum Problem 13 In this problem, the task is to determine the first ten digits of the total sum when adding up one-hundred 50-digit numbers. 37107287533902102798797998220837590 ...

Discover the art of concurrently listening to both an event and a timer in JavaScript

Upon loading the page, a timer with an unpredictable duration initiates. I aim to activate certain actions when the countdown ends and the user presses a button. Note: The action will only commence if both conditions are met simultaneously. Note 2: To cl ...

Discover the importance of Node.js integration with HTML

I am trying to display a Node-js value in an HTML file using the pug engine. In my app.js file: const express=require('express'); const app=express(); var bodyParser = require('body-parser'); app.set('views','views&apo ...

Solving the problem of synchronicity in JavaScript for Angular Translate

Using Angular Translate as a filter in the view has been very effective for me. I have implemented angular-translate-loader-static-files to load external files like locale-en.json. However, I encountered an issue when attempting to do something like this: ...

Is there a way to determine if a value exists within an array of objects?

Is it possible to determine if a specific value is present in an array of objects? I've tried a method, but it always returns false. What would be the most effective way to solve this issue? My approach: var dog_database = [ {"dog_name": "Joey" ...

Adjust the left margin to be flexible while keeping the right margin fixed at 0 to resolve the spacing

To create a responsive design that adjusts based on screen size, I initially set the content width to 500px with a margin of 0 auto. This meant that for a 700px screen, the content would remain at 500px with left and right margins of 100px each. Similarl ...

The validation in AngularJS does not disappear while typing in the text field

After reading through this particular question, I decided to experiment with a way to hide validation messages when typing in a text field. Here's the code snippet I tried: $scope.click = function () { showVal(); } function showVal( ...

Issue arises with highcharts tilemap logarithmic colorAxis when the value is 0

I'm currently working on incorporating a tilemap into highcharts with a logarithmic colorAxis, but I keep encountering highcharts error #10 which states that zero or subzero values cannot be plotted on a logarithmic axis. Is there a way to bypass thi ...

Configuring Vue.js watchers inside a for loop

Exploring the dynamic addition of watchers in Vue.js. The discrepancy between what is desired and what actually happens is demonstrated below in the commented section. As a casual coder, I believe my issue lies more in grasping JavaScript basics rather t ...

Using JavaScript to we can transfer the function result to an HTML input field

Is there a way to display the result of a JavaScript function in an HTML input field? Here is an example form: https://i.sstatic.net/HHHl2.png When I click "Run - Script," the following simple script is executed: <button type="submit" class="btn btn ...

AJAX function designed to send and receive 4 specific variables using the POST

My frustration has been building for hours as I struggle to recall my AJAX! I am attempting to create a function that will send 4 variables via POST to a specified URL, using JavaScript instead of jQuery. Here is an example of what I have so far: functio ...

Unexpected issue with Ustream JSON API and jQuery

Recently, I attempted to execute the following jQuery code: var query = 'http://api.ustream.tv/json/channel/masaiblog/getValueOf/status?jsonp=?'; $.getJSON(query, function(data) { if (data['results'] == 'live') { ...

Using scripted <svg> with <defs> and attempting to reference it via JavaScript results in failure

My goal is to dynamically generate svg path elements in html using JavaScript. I would like to place these paths within a <defs> element so that they can be reused later in <use> xlink:href elements. However, after creating the paths (by pr ...