Ordering Arrays based on a particular attribute

My array includes user points as follows:

let groupRank = [];

userA = ["Sara", "24"];
userB = ["John", "12"];
userC = ["Eddi", "20"];
userD = ["Marry", "13"];

I am looking to rank them according to their points and achieve the following result:

Console.log(groupRank);
//Sara, Eddi, Marry, John

Answer №1

To organize the data, you can construct a 2D array and utilize the sort method to arrange it based on the points located at index 1. Then, employ the map function to extract the names that appear at index 0.

let userArray = [
  ["Sara", "24"],
  ["John", "12"],
  ["Eddi", "20"],
  ["Marry", "13"]
]

const sortedNames = userArray.sort((first, second) => second[1] - first[1])
                         .map(entry => entry[0])

console.log(sortedNames.join())

If you possess all those separate arrays in distinct variables, assemble the 2D array as follows:

let userArray = [ userA, userB, userC, userD ]

Answer №2

  1. Begin by consolidating all arrays into one.
  2. Next, sort the array based on the value at index 1.
  3. Extract only the names from the array using Array#map

let groupRank = [];

userA = ["Sara", "24"];
userB = ["John", "12"];
userC = ["Eddi", "20"];
userD = ["Marry", "13"];
var res = [userA,userB,userC,userD]; //consolidate all in one
res = res.sort((a,b)=> b[1]-a[1]); // sort based on points
res = res.map(a=> a[0]); //extract the names only
console.log(res)

Answer №3

To organize the users based on their rank, you can utilize the sort function to arrange them in an array. During sorting, convert the pointer to a number using the unary operator. The result of the sort function will be an array of arrays. If you require the names only, you can employ the map function to extract the array of names.

let groupRank = [];

let userA = ["Sara", "24"];
let userB = ["John", "12"];
let userC = ["Eddi", "20"];
let userD = ["Marry", "13"];

let allUsers = [userA, userB, userC, userD];

groupRank = allUsers.sort(function(a, b) {
  return +b[1] - (+a[1])
}).map(item => item[0])


console.log(groupRank)

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

Group an object by its name using Java Script/Vue.Js

I am looking to group objects by partial name and assign them to variables data = { SCHOOL-ADMISSION_YEAR: "2021" SCHOOL-SCHOOL_NAME: "ABC SCHOOL" SCHOOL-SCHOOL_LOCATION: "NEWYORK" ENROLLMENT-ADMISSION_YEAR: " ...

Encountering Issue with Node.JS and Socket.IO Example: Debugging Error on MAC OSX Localhost. Static Content File '/socket.io.js' is not loading properly

Recently, I started working with node.js and decided to incorporate the socket.io module. However, I encountered some issues with it not functioning as anticipated. The example that I am trying to replicate can be found at: I realized that the version of ...

Having trouble finding the correct output when searching in the table using regex

I am currently experiencing an issue with my code for searching. When I search the full text, it works fine but when I search for a middle character, it does not work as expected. For instance, searching for "apple" or "ap" works correctly, however, if I ...

Error encountered when attempting to include a foreign key

I am attempting to establish a 1:1 relationship between two tables. The RefreshToken table will contain two foreign keys connected to the Users table, which can be seen in this image: https://i.stack.imgur.com/B2fcU.png To generate my sequelize models, I ...

Is it possible to determine if a style property has been altered

I am looking to identify changes in CSS properties without needing the actual values. I only require the specific style property that has been altered. For example, I need the style property to be stored in a variable, as shown below: document.getElementB ...

Transforming arrays with map or alternative methods in javascript

Below is the JSON object I am working with: { id: 3, cno: 103, username: 'basha', name: 'New Complaint', desc: 'Need bag', storeId: [ 5, 1 ] } My desired output should look like this: [ {id: 3,cno: 103, ...

Guide to utilizing Materialize with Angular 2

For the past 2 days, I've been struggling with an issue. I'm fairly new to Angular 2 and I'm attempting to use Materialize with Angular 2. I managed to resolve a couple of errors that were asking me to update the TypeScript version, which I ...

Testing an Angular factory that relies on dependencies using JasmineJS

I have a factory setup like this: angular.module("myServices") .factory("$service1", ["$rootScope", "$service2", function($rootScope, $service2){...})]; Now I'm attempting to test it, but simply injecting $service1 is resulting in an &ap ...

The display of the selected input is not appearing when the map function is utilized

I am attempting to use Material UI Select, but it is not functioning as expected. When I use the map function, the default value is not displayed as I would like it to be. However, it does work properly when using the traditional method. *** The Method th ...

What is the best way to convert modal window functionality from jQuery to native Javascript?

How can I convert this jQuery code for modal windows into native JavaScript while using data attributes? I am having trouble integrating forEach and getAttribute in my code. I usually rely on jQuery, but now I need to switch to native JavaScript. I apprec ...

Improper headings can prevent Chrome from continuously playing HTML5 audio

Recently, I encountered a peculiar and unlikely issue. I created a custom python server using SimpleHTTPServer, where I had to set my own headers. This server was used to serve .wav files, but I faced an unusual problem. While the files would play in an ...

Is it possible to update the .reduce() method in React similar to how useState() is

Currently, I am immersed in a small project focusing on the "Cart" feature. The only missing piece of the puzzle at this point is calculating the total price for each product. I've managed to calculate it, but when adding multiple units of a single p ...

Using Vue with Firebase to fetch a specific range of data starting from a particular record and ending at the

I am looking to retrieve all records from a certain record to the very last one in my database. ref.orderByChild("date").equalTo("19/11/2020 @ 19:50:29").on("child_added", (snapshot) => { console.log(snapshot.va ...

Unable to modify the value of an HTML dropdown list

My latest project is a website located at pg.wcyat.me (Source code), where I utilized github.com/thdoan/pretty-dropdowns for dropdown menus. Using JavaScript, I am able to dynamically change the values of select lists. For example: document.getElementById( ...

Using React client to accept messages from a Socket.io server: A guide

I have a setup where a Node.js server with Socket.io is used to send messages between React clients. Currently, I can send a message from Client 1 to Client 2, but the recipient must click a button to view the message on their screen. I am trying to make i ...

Switching the keyboard language on the client side of programming languages

I'm interested in altering the keyboard language when an input element changes. Is it possible to modify the keyboard language using client-side programming languages? And specifically, can JavaScript be used to change the keyboard language? ...

What sets apart the information contained within a cell versus the information saved as a double in MATLAB?

I'm puzzled by two variables that appear identical to me, yet one is tagged as <double> and the other as <cell>. It seems like they are being converted using cell2mat in the code. I comprehend that it relates to how data is stored, but I c ...

Error encountered when attempting to utilize the push() method on a two-dimensional

My goal is to arrange database data by their groupID (each with a different groupID in a separate sub-array). However, when I attempt to push the data into an array, I encounter the following error: TypeError: Cannot read property 'push' of unde ...

Issue with jquery curvy corners not functioning properly on Internet Explorer 8

Check out my website at If you view the page in IE8 and then in IE7 compatibility mode, you'll notice a strange issue. The box on the right disappears in IE8 but displays perfectly rounded corners in IE7. I am currently using the jQuery Curvy Corner ...

Creating image galleries with HTML and Javascript loop through the drawImage function to display multiple

I'm currently working on developing a card game using HTML5 canvas, and I've come across an issue with the drawImage function when used inside a loop. It seems like there might be a problem related to closures, but I'm not entirely sure how ...