Organize an array based on its ratio

I am attempting to organize an array based on the win and lose ratio of each player.

This is how my code currently looks:

const array = [{playerName: 'toto', win: 2, lose: 2}, {playerName: 'titi', win: 0, lose: 0}, {playerName: 'tata', win: 3, lose: 1}];
    array.sort((a, b) => a.win / a.lose || b.win / b.lose);
    console.log(array);

The positioning of player 'titi' above player 'toto' in the sorted array is confusing me.

Answer №1

Your sort function has a few issues that need to be addressed. Firstly, when dividing by a.lose and b.lose, you're encountering the problem of division by zero in your sample data resulting in Infinity. Secondly, the callback function for a sort should return either a negative number, 0, or a positive number based on whether a should come before, equal to, or after b. However, due to your current logic, it will always return a positive number. To fix this, consider using the following code snippet:

const array = [{
  playerName: 'toto',
  win: 2,
  lose: 2
}, {
  playerName: 'titi',
  win: 0,
  lose: 0
}, {
  playerName: 'tata',
  win: 3,
  lose: 1
}];
array.sort((a, b) => {
  if (a.win + a.lose == 0) return 1;
  if (b.win + b.lose == 0) return -1;
  return b.win / (b.win + b.lose) - a.win / (a.win + a.lose);
});
console.log(array);

Answer №2

take a look

to provide more clarity:
If the compareFunction(a, b) results in a value greater than 0, then place b before a in the sorted array.

In this particular scenario, using 1/0 leads to a value of Infinity, which is considered true and causes it to skip the calculation for the b part. Returning true has the same effect as returning 1.

Answer №3

Implement a comparison function that sorts players based on the sum of their wins and losses.

const sortPlayers =(a, b) => {
  if (a.win + a.lose + b.win + b.lose === 0) {
    return 0
  } else if (a.win + a.lose === 0 && b.win + b.lose !== 0) {
    return 1
  } else if (a.win + a.lose !== 0 && b.win + b.lose === 0) {
    return -1
  } else if ((a.win/(a.win + a.lose) > (b.win/(b.lose + b.win)))) {
    return -1
  } else if ((a.win/(a.win + a.lose) < (b.win/(b.lose + b.win)))) {
    return 1
  } else {
    return 0
  }
}
const array = [{playerName: 'toto', win: 1, lose: 0}, {playerName: 'titi', win: 0, lose: 0}];
array.sort((a, b) => sortPlayers(a, b));

console.log(array)

Answer №4

Your array sorting solution has been discovered! It's presented in a way that is easy to understand. This particular code snippet arranges the elements in descending order based on the win or lose index parameter. Check out the modified version of your original code below:

const array = [
  {playerName: 'toto', win: 1, lose: 0}, 
  {playerName: 'titi', win: 0, lose: 0}
];
    
array.sort((a, b) => { 
   if(a.win > b.win ||  a.lose < b.lose) { 
      return 1; 
   } 
   return -1;
});
console.log(array);

If you need to change the order, simply swap "<" with ">" and vice versa.

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

Identifying the HTML elements beneath the mouse pointer

Does anyone know the method to retrieve the HTML tag located directly under the mouse cursor on a webpage? I am currently developing a new WYSIWYG editor and would like to incorporate genuine drag and drop functionalities (rather than the common insert at ...

Instructions for showcasing a 404 error page in the event that a back-end GET request to an API fails due to the absence of a user. This guide will detail the process of separating the

I am currently working on an application that combines JavaScript with Vue.js on the front-end and PHP with Laravel on the back-end. When a GET request is made from the front-end to the back-end at URL /getSummoner/{summonerName}, another GET request is t ...

Angular.js is a great tool for showing PDF files on a

I am facing a challenge while trying to incorporate a PDF file into my Angular.js website. The PDF is stored as a blob in a MySQL database and I want to display it as one of the partial views that appear on the main page when a link is clicked. Unfortuna ...

Setting up a global CSS and SASS stylesheet for webpack, TypeScript, Phaser, and Angular: A step-by-step guide

A manual configuration has been set up to accommodate all the technologies mentioned in the title (webpack, typescript, phaser, and angular). While it works perfectly for angular component stylesheets, there seems to be an issue with including a global st ...

Is it not possible to generate HTML tags using jQuery and JavaScript in JSF?

I'm currently working with jsf 2.0 and richfaces 4.0 to develop my application. Occasionally, I incorporate jQuery and JavaScript functions for displaying and hiding elements. However, I've encountered an issue when trying to generate tags within ...

CSS navbar with a unique design: Issue with List Hover not Persisting

I'm facing a common issue with a pure CSS navbar. I have constructed a navbar using ul and li elements, but I am unable to make the menus stay visible when I hover over them. The problem lies in the fact that the menu opens only when I hover over the ...

In my development environment, the page does not have scroll functionality, but in the production environment, it is scrollable

Whenever I open a table or any other element with overflowing content, I encounter an issue with the scrolling bar. Even though the CSS includes overflow-y: scroll;, the scroll bar on the right remains in gray and does not allow me to scroll down when the ...

Trouble encountered while trying to utilize a Promise to define a global variable

I am attempting to populate a global variable using a function and then call subsequent functions after the data is retrieved. Below is the current code I have: $(function () { var jsonData = {}; var dataRetrievalPromise = function () { r ...

An innovative way to display or hide a div depending on the multiple selections made in a select2 jQuery field

A select2 jQuery dropdown menu is set up with two options: *For Rent *For Sales If the user selects 'For Rent', specific fields will be displayed below it, as well as for 'For Sales'. The challenge arises when both options are ...

Exploring and accessing the properties of objects in JavaScript

While attempting to access the email and password fields, an unexpected '0' seems to have appeared. The object retrieved from RethinkDB appears fine without this '0'. However, when using Lodash's _.assign() method like so: var use ...

Unleashing the Power of RxJS with OR Conditions

I am working with two Observables. For instance, I am waiting for either an HTTP POST call or a WebSocket call to return so that I can proceed. Once either call returns, I need to verify the information until a certain condition is met. In the following e ...

Can a shape similar to an inverted circle be created using CSS and jQuery?

I'm stumped on how to create an inverted circle in the corners. I've included a picture for reference. https://i.stack.imgur.com/jeNdh.jpg Is it feasible to achieve this effect using CSS3 or maybe jQuery? ...

The Textfield component in Material UI now automatically sets the default date to the current date when using the "date" type

I am using Material UI's textfield with the type set to "date" and I'm experiencing an issue where the date defaults to the current date instead of mm/dd/yyyy. Is there a way to prevent this behavior and display mm/dd/yyyy when the user loads the ...

The click event that is dynamically added is triggered multiple times

On clicking a button, I am dynamically adding a row to an HTML table. The row contains a cell with a list item (li) element which has a click event assigned to it. However, when I click on the list item, the event fires multiple times and I'm unsure w ...

Using maxDate in Material UI DatePicker Component to set a maximum date limit

I'm having a tough time getting the maxDate property to function properly on the Material UI DatePicker component. It should disable dates after the specified maxDate. In my situation, I needed to set the maxDate to +60 days from the current Date(), ...

Lagging speeds in client-side template rendering using Rivets.js

I have a function that renders an array of around 1000 objects, but the html bindings are causing significant performance issues. It currently takes about 5 seconds to complete rivets.bind(). Does anyone have any recommendations for improving performance? ...

Is it possible to utilize mathematical operators such as multiplication, division, addition, subtraction, and exponentiation to transform a non-zero numerical value into

I am currently working with Oracle Siebel software which supports JavaScript expressions using only specific operators such as multiply, divide, subtract, add, and XOR (*, /, -, +, ^). Unfortunately, other operators like ! or ? : are not available for use. ...

Utilizing ngx-bootstrap to enhance Bootstrap dropdown functionality

I initially tried to set up ngx-bootstrap in Angular 2 by using the following command: npm install ngx-bootstrap bootstrap --save Then, I included these lines in angular-cli.json: "../node_modules/bootstrap/dist/css/bootstrap.min.css". In app.compone ...

I am looking to optimize my JavaScript function so that the console.log structure is functioning correctly. What changes can I make to

I've been trying out this method to tackle the issue, however, my console.log isn't providing the expected output. What adjustments should I make? const executeCalculator = ({ x, y, operation }) => { let calculator = { x: this.x, ...

Attempting to retrieve the name of my controller and action within a JavaScript file

After checking out the Stack Overflow link here, I came across a suggested solution: var controllerName = '@ViewContext.RouteData.Values["Controller"].ToString()'; However, despite implementing this code in my JavaScript file, it does not yield ...