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

Styling a Pie or Doughnut Chart with CSS

I am working on creating a doughnut chart with rounded segments using Recharts, and I want it to end up looking similar to this: Although I have come close to achieving the desired result, I am encountering some issues: Firstly, the first segment is over ...

Experimenting with Date Object in Jest using Typescript and i18next

I have included a localization library and within my component, there is a date object defined like this: getDate = () => { const { t } = this.props; return new Date().toLocaleString(t('locale.name'), { weekday: "long", ...

When attempting to parse a file name using a regular expression in TypeScript (or even plain Node.js), the unexpected outcome is a

Looking to extract language information from a filename? Check out this simple construct: The structure of my language.ts model is as follows: export interface Language { language?: string; region?: string; } The function designed for parsing the fi ...

Exploring ways to validate the existence of a class in HTML table elements

If I want to verify if each element has a specific class when creating tables and clicking on the corresponding cells above them, This is what I have tried. However, it did not work as expected. How can I make this work correctly? What am I missing her ...

When the appdir is utilized, the subsequent export process encounters a failure with the error message "PageNotFoundError: Module for page /(...) not

I have implemented NextJS with the experimental appDir flag and organized my pages in the following manner: https://i.stack.imgur.com/M7r0k.png My layout.tsx file at the root and onboard look like this: export default function DefaultLayout({ children }) ...

Exploring the functionality of the $.each jQuery iterator. Can someone clarify the distinctions between these two methods?

Having vertices as an array of google.maps.LatLng objects means that they should return latlng points. The first code snippet works perfectly fine, however, I encounter issues when using the second one. // Iterate over the vertices. for (var index =0; ind ...

Looking to streamline a JavaScript function, while also incorporating jQuery techniques

I've got this lengthy function for uploading photos using hidden iFrames, and while it does the job well, it's quite messy. I'm looking to simplify it into a cleaner function with fewer lines of code for easier maintenance. function simplif ...

What is the method in JavaScript for a child function to trigger a Return statement in its parent function?

I have encountered a unique problem. I need to retrieve some data downloaded via ajax and return it, but neither async nor sync modes are fetching the data in time for the return. Is there a way to call the return from a child function to the parent func ...

Step-by-step guide on utilizing User scripts with the $window.open function in AngularJS

I am looking to initiate the following action - (for example: Upon clicking a button, it should direct to this , similar to how payment gateways function) and then, I need to input the user script below: getRealData('{"mailing":{"postalCode":"1 ...

Aligning arguments within the function signature

Is it possible to specify in TypeScript that the method 'foo' always expects FooData, etc. for the following code snippet: const search = (data: FooData|BarData|BazData, method:"foo"|"bar"|"baz") => { //Perform some common operations retu ...

Executing numerous tests on a single response using Node.js along with Chai, Mocha, and Should

I have a setup similar to the one below that allows me to perform a series of API tests using Mocha. While this method works well, it involves making an individual API call for each test. My goal is to streamline the process by utilizing the same API cal ...

Comparison of various nodejs scripts

Snippet One net.createServer(function(socket){ socket.on('data',function(id){ getUserDetails(function(){console.log(id)}); }); }); function getUserDetails(next){ next(); } Snippet Two net.createServer(function(socket){ ...

NodeJS - The function app.listen is not defined in this context

I've come across a similar question before, but the answers provided didn't help me resolve my issue. The error message I'm getting is "TypeError: app.listen is not a function"; Here's my full code below. Thank you in advance for your ...

Leverage angular-translate to establish placeholder text upon blurring

Just starting out with Angular and facing the challenge of implementing localization in my project. I have a lot of input fields that need their placeholders translated. In my HTML, I'm trying to achieve this: <input type="email" placeholder="{{ & ...

Setting up an SSL certificate for an Express application: A step-by-step guide

I am currently trying to set up my Express server in order to pass the SSL certificate and transition from http to https. After going through the Express documentation, I still haven't been able to find a suitable solution. While some suggestions lik ...

What is the Correct Way to Send Functions to Custom Directives in Angular 2 Using TypeScript?

I am relatively new to Angular 2. I am currently in the process of upgrading my application from AngularJS and focusing on completing the UI/UX development. There is one final issue that I am seeking help with, and I appreciate any assistance provided. Cu ...

Accessing the i and i+1 elements within a ng-repeat iteration

I'm currently learning Angular and struggling with a seemingly simple issue. My goal is to achieve the following HTML structure in AngularJS: <div> <div> {{bar[i]}} {{bar[i+1]}} </div> <div> {{bar[i+2]}} ...

The feature of Nuxt 3's tsconfig path seems to be malfunctioning when accessed from the

Take a look at my file structure below -shared --foo.ts -web-ui (nuxt project) --pages --index.vue --index.ts --tsconfig.json This is the tsconfig for my nuxt setup. { // https://v3.nuxtjs.org/concepts/typescript "exte ...

Information is not transferring to Bootstrap modal

I attempted to send a value to a modal by following the instructions on the Bootstrap documentation here. However, I am facing an issue where the data is not being successfully passed. To trigger the modal, use the following button: <button type=" ...

What causes Gun.js to generate duplicate messages within a ReactJs environment?

I need assistance with my React application where gun.js is implemented. The issue I am facing is that messages are being duplicated on every render and update. Can someone please review my code and help me figure out what's wrong? Here is the code s ...