How can we organize and display the data from two linked arrays, one containing player names and the other containing

Looking for help on how to rank 3 players based on their scores using arrays. I've hit a roadblock and need guidance!

Here's a brief example:

Player 1 : Taylor
Score Taylor : 15

Player 2 : Jordan
Score Jordan : 20

Player 3 : Alex
Score Alex : 18

After ranking, we should have:

The first => Jordan with 20 scores
The second => Alex with 18 scores
The third => Taylor with 15 scores

Below is the code snippet I'm currently working on:

function main() {
    var players = new Array();
    var scores = new Array();

    for(i = 0; i<3; i++) {
        players[i] = prompt("Player " + (i+1) + " : ");
        scores[i] = prompt("Score " + (players[i]) + " : ");
    }
}   

Appreciate any assistance in advance!

Answer №1

When faced with the challenge of splitting data into two arrays, one solution could involve using a custom sorting function along with an additional array that stores indices corresponding to the elements in the other arrays:

execute();

function execute() {
  var users = new Array();
  var points = new Array();
  var rankings = new Array();
  for (var i = 0; i < 3; i++) {
    rankings[i] = i;
    users[i] = prompt("User " + (i + 1) + " : ");
    points[i] = prompt("Points for " + (users[i]) + " : ");
  }
  sortIndexedArray(3, rankings, points);
  for (var i = 0; i < 3; i++) {
    var ithUser = users[rankings[i]];
    var ithPoints = points[rankings[i]];
    console.log(ithUser, ithPoints);
  }
}

function sortIndexedArray (n, toBeSorted, toBeCompared) {
  for (var i = 0; i < n - 1; i++) {
    for (var j = i + 1; j < n; j++) {
      var a = toBeCompared[toBeSorted[j]];
      var b = toBeCompared[toBeSorted[i]];
      if (a < b) {
        var min = toBeSorted[j];
        toBeSorted[j] = toBeSorted[i];
        toBeSorted[i] = min;
      }
    }
  }
}

Here is a demonstration of how the code above operates:

users = ["Alice", "Bob", "Charlie"];
points = [5, 7, 4];
rankings = [0, 1, 2];
sortIndexedArray(3, rankings, points);
console.log(rankings);
// [2, 0, 1]
console.log(users[rankings[0]]);
// "Charlie"
console.log(points[rankings[0]]);
// 4

Answer №2

Use this code snippet to create a sorted array of players with names and scores

function generateSortedPlayerArray()
            {
                var players = new Array();

                for(i = 0; i<3; i++){
                    let player = {};
                    player.name = prompt("Enter Player " + (i+1) + "'s name: ");
                    player.score = prompt("Enter " + player.name + "'s score: ");
                    players[i] = player;
                }

                players.sort(function(a,b){
                     if (a.score < b.score)
                         return -1;
                     if (a.score> b.score)
                          return 1;
                     return 0;
                })

                console.log(players);

            } 

Answer №3

To efficiently manage and organize users, consider storing each user as an object within an array in the following manner:

function storeUsers(){

    var userList = [];
    for(var i = 0;i<3;i++){
      var user = {};
      user.name = prompt("Enter user name");
      var ranking = prompt("Enter user ranking");
      user.ranking = parseInt(ranking);
      userList.push(user)
    }
    
    console.log("User List");
    userList.forEach(function(user){
      console.log(user.name,user.ranking);
    });
    //Sort the list based on ranking
    userList = userList.sort(function(uA,uB){
      return uA.ranking - uB.ranking;
    });
    userList.forEach(function(user){
      console.log(user.name,user.ranking);
    });
} 

storeUsers();

Answer №4

Here is a simple implementation using the push method to add objects to an array and the sort method to sort the array based on the score. Take a look at the code snippet below.

var array=[];

function add(){
    var player={};
    player.name=prompt("Player " + (array.length+1) + " : ");
    player.score=parseInt(prompt("Score " + (player.name) + " : "));
    array.push(player);
    array.sort((a,b)=>a.score<b.score)
    console.log(array);
}
<button onclick="add()">Add Player</button>

Answer №5

Instead of using separate arrays, it is recommended to use an array of objects like this:

let data = [
  {name: 'Jeremy', score: 12},
  {name: 'Julien', score: 18},
  {name: 'Olivia', score: 22}
];

You can then easily sort and display the results using .sort():

let data = [
  {name: 'Jeremy', score: 12},
  {name: 'Julien', score: 18},
  {name: 'Olivia', score: 22}
];

data.sort((a, b) => b.score - a.score);

console.log(`The first player is ${data[0].name} with ${data[0].score} points`);
console.log(`The second player is ${data[1].name} with ${data[1].score} points`);
console.log(`The third player is ${data[2].name} with ${data[2].score} points`);

If you prefer to stick with 2 separate arrays, you can still combine them into an array of objects and display the sorted results.

let players = ['Jeremy', 'Julien', 'Olivia'];
let scores = [12, 18, 22];

function printResult(playersArr, scoresArr) {
  let combinedArray = playersArr.reduce((arr, name, index) => (arr.push({name, score: scoresArr[index]}), arr), [])
           .sort((a, b) => b.score - a.score);
                 
  console.log(`The top player is ${combinedArray[0].name} with ${combinedArray[0].score} points`);
  console.log(`The second player is ${combinedArray[1].name} with ${combinedArray[1].score} points`);
  console.log(`The third player is ${combinedArray[2].name} with ${combinedArray[2].score} points`);
}

printResult(players, scores);

Helpful Resources:

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 compare two 2D arrays in JavaScript?

Having an issue comparing two 2D arrays in javascript, looking to output "true" if the arrays are the same. This is the code I experimented with: ` function check(){ if (data.every() === solution.every()){ alert("example"); } else { ...

Previewing multiple images with multiple file inputs

I am trying to find a way to preview multiple images uploaded from different inputs. When the button is pressed, the content from a textarea containing <img src="$img" id="img1"> is written inside a div called seeimg. The IDs for these images range f ...

"Clicking the button will clear the values in the input fields

I have encountered a strange issue that I've never seen before. When I try to input the value of scope upon clicking on <a>, everything works fine. However, if I have entered values in other inputs and then click on <a> again, the values i ...

Most effective method for integrating a JS module across all browsers

I have created a robust library that I want to integrate into a different web project. This library handles all its dependencies and consists of js, css, and html files. My ideal scenario would be to package it as an npm module and simply use import to in ...

Executing function with ng-click in AngularJS only on the second click of the button

Currently, I am studying AngularJS and working on an exercise that involves using the ng-click function. Strangely, I am only able to view the result after clicking upload for the second time. I am trying to display my json content but it's not workin ...

Navigating - Utilizing dot-notation to reach the top-level function in Express

If we want to use express in a basic javascript file, all we need to do is add the following two lines of code at the beginning (after installing it through npm): var foo = require('express'); var app = foo(); According to the express API guide ...

The VueJS Chosen directive fails to refresh when new options are selected

Struggling to populate my jQuery Chosen dropdown field with AJAX data using VueJS. Unfortunately, when trying to update the values, the Chosen dropdown does not reflect the changes. I've experimented with different approaches, including manually trig ...

Accessing the jQuery Ajax success variable

I have a PHP function that returns an array with an element error containing the value 'ERR': var updatePaymentType = function(plan_pt_id, pt_id){ var error = null; var data = new Object() data["function"] = "update"; ...

Having difficulty resolving issues with the chat box (div) scroll bar staying fixed at the bottom

I am currently working on a chat application and I am facing an issue with fixing the scroll bar at the bottom of a div when loading my PHP file. I have already written a script to achieve this, but despite accessing it using CSS Id, I am having trouble ge ...

Localhost is unable to process AngularJS routes containing a dot in the URL

When using the route provider and setting this specific route: .when('/:name/:id', { It successfully navigates to my desired path and executes the code when I enter: https://localhost.myapp.com:9000/Paul/123 However, it fails to work with this ...

I am unable to utilize the backspace function within a text box generated by JavaScript

I have created a dynamic form using JavaScript that includes buttons and one text input field. However, the issue is that to delete the text entered in the input field, one must highlight the text and then type over it instead of being able to simply use t ...

The Angular controller failed to return a defined value

I recently took over a legacy VB.Net application and noticed that both the ng-app and ng-controller directives are present on the HTML element in the root master page: <html runat="server" id="html" ng-controller="MasterController"> The ng-app attr ...

Adjusting the color of an HTML slider button as it moves

In my setup, I have a straightforward slider that I plan to use for controlling the movement of a stepper motor based on the slider's position. I wanted to give the website where this will be hosted a professional look, so I've spent quite some t ...

The collapsed feature of the Bootstrap 4 Navbar is not functioning as

Recently, I delved into the world of Bootstrap 4 and decided to create a collapsing menu. Everything seemed to be working fine when I clicked the button and saw the content display perfectly. However, things took a turn for the worse when I tried to collap ...

what is the method to extract the value of a JSON object nested within another JSON object

Can someone please assist me? "_attachments": { "kiran.jpg": { "content_type": "image/jpeg", "revpos": 6, "digest": "md5-mEsoX4ljN1iJlF2bX1Lw2g==", "length": 4601, "stub": true } } I ...

Create a log table specifically for tracking changes made to the drop-down menu

I need to create a Change log table that will track any changes made in the drop-down menu. For instance, I am working on a worksheet with a select menu called Results which includes options like Positive, Negative, Unknown. I want the system to log any ch ...

Having trouble executing an npm script - getting an error message that reads "Error: spawn node_modules/webpack/bin/webpack.js EACCES"

After installing and configuring Linux Mint, I encountered an error when trying to run my project with the npm run dev command. The error message "spawn node_modules / webpack / bin / webpack.js EACCES" keeps appearing. I have attempted various methods fo ...

Place a checkbox at the start of each table cell

Is there a way to add a checkbox before the text in the first cell of each row in an HTML table using jQuery? I attempted this method: $("table td:first-child").each(function() { $(this).prepend('<input type="checkbox" class="basic-kpi-row"/&g ...

What is the proper way to arrange an array in this style?

I'm curious about how to properly format this particular array. Take a look at the array below as an example: [ itemone:"One", itemtwo:"Two" ] My goal is for it to display like so: itemone - One itemtwo - Two ...

Is there a way to customize jqwidgets jQuery grid cell classes/styles based on row ID and column name?

{ text: 'sell', datafield: 'Sales', width: '3%', columntype: 'button', filterable: false, cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) { return &apos ...