Generate a fresh array showcasing the rankings of the initial array

If we take the array [10, 5, 20] as our input, according to my function, the output should be [2, 3, 1]. This is because 10 is the second largest number, 5 is the third largest, and 20 is the largest.


function determineRankings(arr){
  const result=[];
  let newArr=arr.sort((a,b)=>b-a);
  
  for (let i=0;i<arr.length;i++){
    for (let j=0;j<newArr.length;j++){
      arr[i]===newArr[j]? result.push(j+1): console.log('');
    }
  }
  
  return(result);
}

When using my function with the input array of [10,5,20], I get the output [1,2,3], however the expected output is: rankings([10, 5, 20]); // [2, 3, 1] rankings([6, 8, 1, 12, 4, 3, 9]); // [4, 3, 7, 1, 5, 6, 2]

Answer №1

If you want to organize the elements in an array, one approach is to sort the array and then align the indexes with the original array.

Adjusted for scenarios involving duplicate numbers

let numberArray = [15, 25, 10, 15, 10]
   , uniqueArray = [...new Set(numberArray)]
   , organizedArray = [...uniqueArray].sort((a, b) => a - b)
   , dataIndex = numberArray.map(num => organizedArray.indexOf(num) + 1)

console.log(dataIndex)

Answer №2

To prevent duplicate values with different ranks, one approach is to sort the values and then filter out duplicates.

function generateRankings(arr) {
  const sortedArr = [...arr]
      .sort((a, b) => b - a)
      .filter((b, i, { [i - 1]: a }) => a !== b);
 
    return arr.map(value => sortedArr.indexOf(value) + 1);
}

console.log(generateRankings([10, 5, 20])); // [2, 3, 1]
console.log(generateRankings([6, 8, 1, 12, 4, 3, 9])); // [4, 3, 7, 1, 5, 6, 2]
console.log(generateRankings([10, 5, 20, 10, 20]));

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

Remove the JSON object by comparing IDs between two JSON objects in JavaScript or Node.js, deleting it if the ID is not found

let data = fetchData(); let anotherData = getAnotherData(); let result = data.reduce((accumulator, current) => { if (!accumulator[current.system.name]) { accumulator[current.system.name] = {}; } let detailsObject = {}; Object.keys(current. ...

What could be causing the type error to show up in my JavaScript file?

Why is this error occurring? I am currently studying web development through Colt Steele's web bootcamp and encountered this issue. $ node user.js mongo connection is open D:\web development practice\mongoose_relationship\Models\u ...

Steps for integrating Laravel pagination into a Bootstrap table with the wenzhixin plugin

I am facing an issue where the laravel pagination() function returns data in a format that is not understood by bootstrap table. How can I resolve this problem? Route: Route::post('/student-statement', [StatementController::class, 'index&ap ...

What techniques can I use to implement a C++ array in this situation?

How can I implement C++ Arrays in this scenario? The question above is about the format. https://i.sstatic.net/GG3R7.png How can I use C++ Arrays for this situation? The question described in the image is being referenced. #include <iostream> ...

What is the best way to change a Buffer array into hexadecimal format?

After making a call to one of my API endpoints, I am receiving a Buffer array in a JSON object. My goal is to convert this array into a more user-friendly format such as hex so that I can easily compare them. Below is a snippet of the current object struct ...

How to verify the parent nodes in a jstree

I have implemented a two state jstree. However, I am encountering an issue where it is not possible to select any other node in relation to a node. My goal is that when I click on a specific node, all of its parent nodes should also be checked. Any assist ...

Leveraging Unique Identifiers in Real-Time Namespace with SocketIO

I am in the process of developing a multi-tenant chat application and my goal is to have each tenant connect to their own namespace in socket io. I am using the unique identifier of the tenant, which is a UUID (for example: 5d056752-6643-4300-926f-5bcd5ed6 ...

Fortran: Versatile Array Filtering

When working with Fortran, our code looked like this: !vectors w,q are of the same size ... w = ... !a vector of integers [0,...,n) if (allocated(t)) deallocate(t); allocate(t(count(w/=0))) t = pack(q, w/=0) m = count(t>0) if (allocated(b)) de ...

Attempting to dynamically change the text of a button in JavaScript without any user interaction

I have created a button function that displays a word's definition when clicked. However, I am now attempting to modify it so that the definitions are shown automatically every few seconds using "SetInterval" without requiring a click. I am unsure of ...

Error in Node Express server: Status code 0 is not valid

As a beginner node.js/js programmer, I am encountering an error code while trying to make a POST request on my application. The error message reads as follows: Error: [20:22:28] [nodemon] starting `node app.js` Running server on 3000 Mon, 27 Jun 2016 19:2 ...

What is the process of specifying that an Angular directive must act as a child directive within a particular directive in Angular?

I am currently developing a directive for AngularJS. How can I specifically configure it to require being a child of directiveA? For instance, consider the following example: <my-modal> <m-header>Header</m-header> </my-modal> ...

JQuery spinner not triggering OnChange event for Input Type = Number

I am dealing with an <input type="number" class="post-purchase-amount"/>. Currently, I have implemented an ajax call that triggers when the value is changed. It works perfectly fine when I manually change the value by typing in the text box. Howeve ...

Selective Circle Appending Techniques

I am having some issues with my bubble chart code. The data file I am working with contains instances where the GDPperCapita and/or LifeExpectancy values are either 0 or NaN, causing problems when appending circles to the chart. I would like to know if th ...

Effective strategies for integrating Bootstrap and AngularJS without relying on jQuery

Currently exploring AngularJS after experimenting with Twitter's Bootstrap. I appreciate Bootstrap for its simplicity, sleek design, and mobile-friendliness. On the other hand, I have noticed a trend where people recommend using AngularJS over jQuery, ...

Using jQuery to call a function in processing.js from JavaScript or jQuery

I have set up an application that needs to call a processing.js function, but I am having trouble accessing the processing instance. Here is my setup - in my HTML, I have a link that, when clicked, should trigger the processing function: <div id="wrapp ...

"Create a Vue element containing a trio of buttons each displaying a distinct numeral

I am currently dealing with a component that generates three items (boxes) each containing three buttons (created using v-for). The issue I am facing is that when I click on a button, all the numbers inside the buttons change simultaneously. I want to be a ...

Error in Typescript: Cannot assign type 'number' to type 'never'

I encountered an issue related to 'Type 'number' is not assignable to type 'never'.' 'Type 'number' is not assignable to type 'never'.' 'Type 'string' is not assignable t ...

Display PDF file retrieved from the server using javascript

I am currently working on a web application using JavaScript, jQuery, and Node.js. I need to receive a PDF file from the server and display it in a new browser window. While I believe I have successfully received the file on the client side (the window sh ...

Make the source transparent to allow the background to shine through

Is there a way to make the source image of an img tag transparent, allowing the background image to show through? For example, if I have this html: <img src="my_image.jpg" height="200" width="300" style="background:url(img/bg.jpg) repeat;" /> I am ...

Navigating the world of vue-toastification is as easy as pie

I recently made the transition from using vue 3 to nuxt 3 for my project. In vue, I was utilizing the vue-toastification module but after migrating to nuxt, I'm facing difficulties importing it correctly into my code. Here's a snippet of how I wa ...