Sorting a targeted section of an already organized 2D Array based on updated values, solely if the initial sorted values align in Javascript

A challenging scenario I need help with involves an array containing objects, each with a score and a rank as shown below:

    [
        { "score": 20, "rank": 12 }, 
        { "score": 20, "rank": 7 },
        { "score": 34, "rank": 4 }
    ]

To begin with, I must organize this array in descending order based on the score and then store it in a 2-dimensional array.

    [34, 4]
    [20, 12]
    [20, 7]

However, the challenge arises when there are multiple objects with the same score. In such cases, I want to further sort them based on their ranks, with the object having the lowest rank having a smaller index number. This should result in the following arrangement:

    [34, 4]
    [20, 7]
    [20, 12]

Despite attempting various methods, I have not been able to find a satisfactory solution to achieve this sorting. Any assistance on this matter would be greatly appreciated.

Answer №1

To determine the difference between the score of two objects, we first check if it is equal to 0. If it is, then we return the difference between their rank. Otherwise, we return the difference between their score.

const arr = [
    { "score": 20, "rank": 12 }, 
    { "score": 20, "rank": 7 },
    { "score": 34, "rank": 4 }
]

let res = [...arr]
             .sort((a,b) => (b.score - a.score) || (a.rank - b.rank))
             .map(x => [x.score,x.rank]);
console.log(res)

Answer №2

All you need to do is utilize the power of lodash to order your data by two different fields.

Answer №3

To simplify the array, you can first organize it and then apply the Object.values method using the map function:

const arr = [
    { "score": 20, "rank": 12 }, 
    { "score": 20, "rank": 7 },
    { "score": 34, "rank": 4 }
]

let result = arr.sort((a,b) => (b.score - a.score) || (a.rank - b.rank))
  .map(x => Object.values(x))

console.log(result)

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 most efficient way to enable seamless communication between sibling components in Vue.js 2?

Just starting out with Vue.js 2 and I'm really enjoying it so far despite being new to it. Currently using the latest version. I've begun working on my first larger application and ran into a scenario right off the bat where I have a main app co ...

What is the best way to navigate back on a button click in jquery AJAX without causing a page refresh?

Is there a way to navigate back without refreshing the page? I am fetching data dynamically using AJAX, but when I try to go back using the browser button, it takes me all the way back to the starting point. Let's look at the situation: 3 Different ...

Exploring a JSON file to generate a customized array for implementing autocomplete functionality in jQuery

I'm currently working on developing an autocomplete feature for a search bar that will display names of places in Norway. The data is being fetched from a REST API URL provided by a third party. As an example, when the input is "st" there are two res ...

What are the steps to rejuvenate a liferay portlet?

I am attempting to create a link that refreshes a Liferay portlet, but unfortunately it is not working as expected: <a href="javascript:Liferay.Portlet.refresh('#p_p_id_portletname')">link</a> Can someone help troubleshoot this i ...

Understanding Aspect Ratios in CSS for Div Containers and their Components

I am crafting an HTML5 game without the use of canvas and aiming to maintain a 16:9 aspect ratio within my div. Thanks to javascript, achieving this is straightforward and it functions flawlessly. However, the elements inside the div occasionally appear to ...

Troubleshooting problem with JSON array value in Petfinder's AJAX request

$(document).ready(function(){ var url = 'http://api.petfinder.com/shelter.getPets?key=99392cbf55ee6b2f9b97ed375eca907d&id=WI22&status=A&output=full&format=json'; $.ajax({ type : 'GET', ...

PHP: Exploring the Process of Iterating Through an Array with Nested Arrays for Database Insertion

I'm currently working on extracting data from an icalendar file obtained from AirBnB, processing the values, and inserting them into our MySQL database. After successfully parsing the ical file using the PHP Class iCalEasyReader, I have managed to ex ...

Retrieve the array of strings from the current activity and pass the chosen item to a different activity on an Android

Hey there! Today I have a query regarding string arrays in Android development. I have created an activity with two buttons, and in my strings.xml file, I have defined a string array with two items. What I want to achieve is to display each item from the ...

When a radio button is chosen, multiple text fields must be completed in order to validate the form

I am working with a set of 3 radio buttons. If the last option, labeled "In Home," is chosen, then all 4 of the text fields must be filled in for the form to validate. While I have found information on how to achieve this with checkboxes or a single text f ...

This issue with ng-include not functioning properly in Chrome but working fine in Firefox

My code is running only in Firefox and not working in Chrome. HTML Code <div ng-controller="myController1"> Select View: <select ng-model="employeeview"> <option value="1.html">1</option> < ...

Iterate over the JSON data and evaluate the timestamps for comparison

I am attempting to iterate through this JSON data and compare the "start_time" and "end_time" values to ensure that there are no overlaps. However, I am struggling to implement this functionality. While researching, I came across a resource on how to vali ...

What is the process for displaying a document file in an iframe that is returned from a link's action?

I have a main page called index.cshtml. This page displays a list of document files along with an iframe next to it. My goal is to load the selected document file into the iframe when I click on any item in the list. However, currently, when I click on a d ...

In what cases does modelObject.save() update a database document aside from when the modelObject was retrieved from the database?

Let's consider an example where we have a User model defined with a specific schema: var UserSchema = new Schema({ username: String, email: String } mongoose.model('User', UserSchema); If we want to update a user using the save me ...

Using regular expressions to replace all special characters, excluding dots

$('#price').keyup(function(){ $('#price').val($('#price').val().replace(/[_\W]+/g, "-")); }) Experience it firsthand here: http://jsfiddle.net/2KRHh/6/. In the scenario above, special characters are eliminated. ...

Looking for a straightforward way to incorporate a "Read more" and "Show Less" functionality into a Wordpress site using Javascript?

As a last resort, I am seeking a quick and simple fix. I have been experimenting with Javascript to implement a 'Read more...' & '... Read Less' feature on six different sections of a single page. The goal is to display only the fi ...

Start a Draft.js Editor that includes an unordered list feature

I am trying to pre-populate a draft.js editor with an unordered list made from an array of strings. Here is the code I have so far: const content = ContentState.createFromText(input.join('*'), '*') const editorState = EditorState.crea ...

Performing simultaneous updates to multiple records using CAML/jQuery in Sharepoint (Batch updates)

I am working on updating multiple records in Share Point using jQuery and CAML queries. While it's easy to update a single record with the current code, I need to handle 20 Products simultaneously for this particular project. Instead of looping throug ...

Refresh the DIV element that houses dynamically generated <ul> HTML content after submitting new inputs

UPDATE: After delving into the code of nested include files in the child PHP file, I've identified conflicts with the parent PHP include files. This means that the child PHP file/div relies on the parent being refreshed, preventing me from refreshing ...

Implementing Object.somefunction() in ngFor with Angular

In my Angular project, I am using an ngFor loop to iterate over keys generated by Object.keys() in the following code snippet: <ul id='nav-tablist' class='tabrows'> <li *ngFor="let tab of obj.keys(tabList)"> ...

When using Node.js, Express.js, and MongoDB, ensure that the route.post() function is provided with proper callback functions instead of

I've been working on setting up a MEAN (MongoDB, Express, Node.js, Angular 6) application. I'm trying to post user signup form data to a MongoDB database, but I keep getting an error message. This is my first time working with the MEAN stack and ...