Arrange the array in ascending order based on two criteria

Similar Question:
Function for sorting an array of objects

While coding the script, encountered a challenge with sorting an array. There is an array consisting of objects:

[{gold: false, range: 1601}, {gold: true, range: 13}, {gold: false, range: 375}, {gold: true, range: 601}

The desired order is:

[{gold: true, range: 13}, {gold: true, range: 601}, {gold:false, range: 375}, {gold: false, range: 1601}]

The objective to achieve is to sort the keys based on increasing range. However, if the gold key value is true, those should be at the beginning.

Answer №1

Here's a neat way to sort your array:

yourArray.sort(function(a, b){
    return a["gold"] == b["gold"] ? a["range"] - b["range"] : a["gold"] ? -1 : 1;
});

Alternatively, you could use this approach:

yourArray.sort(function(a, b){
    return  b["gold"] - a["gold"] || a["range"] - b["range"];
});

The second method is pretty awesome actually)) You can apply this pattern to any number of fields in your object, prioritizing them by importance. For ascending order, use a["..."] - b["...], and for descending order, use b["..."] - a["..."].

Answer №2

Give it a shot

let elements = [{diamond: false, limit: 1302}, {diamond: true, limit: 45}, {diamond: false, limit: 298}, {diamond: true, limit: 501}], 
    organizer = function(x, y) {
      if(x.diamond && !y.diamond) {return -1;}
      if(!x.diamond && y.diamond) {return 1;}
      return x.limit - y.limit;
    };

elements.sort(organizer);

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

Trouble with basic AJAX form submission

I have created a basic form and AJAX function to send the form data. However, the data is not being posted as expected. Can someone assist in identifying the issue? Fiddle: https://jsfiddle.net/onyeLp4d/2/ HTML <div id="lp-pom-form-25"> ...

`Count the number of rows needed to accommodate text line breaks within a div element`

Is there a method to determine the number of lines that text breaks into using the CSS property word-break: break-all? For example, if I have a div like this: <div>Sample text to check how many lines the text is broken into</div> And the corr ...

Struggling to sift through words within the strainer

I attempted to use the toLowerCase method for filtering words and domain names, but I keep receiving an empty array. I used the toLowerCase method to ensure that data containing capital letters or searched by capital letters are converted to lowercase. Bel ...

What could be causing the input field state to remain static even as I type in the MUI textField?

In my React.js component, I am facing an issue where the textField is not updating when I try to type anything. Upon debugging, I discovered that when the first character is entered, the component re-renders and loses its previous state, causing the textF ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

Server.js node is unresponsive and throwing an error message

Currently, I have started working with expressJs nodeJs but I am facing an issue at the beginning when trying to run the node server.js command. It seems like there might be a missing module that needs to be installed, but I am unsure which one is missing. ...

Issue encountered with updating canvas texture twice in A-Frame and pdf.js while operating in virtual reality mode

Using the power of A-Frame and pdf.js, I embarked on a quest to build an incredible VR application for viewing PDF files. Everything seemed to be working seamlessly on my desktop - flipping through PDF pages, rendering them onto a canvas, it was a sight to ...

Verifying Angular (2+?) Compatibility: Opening and Closing Material mat-menu on Hover [GUIDE]

After extensive research, I tried various methods to hover a material menu to display its options. However, the solutions I came across were either too complicated or ineffective. Therefore, I decided to develop my own solution by combining elements of e ...

Maintaining the user interface state while utilizing $resources in AngularJS

For my app, users have the ability to create and delete items. I've implemented $resources for this functionality, which is working really well. However, I'd like to implement a loading screen that appears whenever a request is being processed. ...

During the second request, Ajax is unable to retrieve any data

Currently, I am working on a calendar project where I utilize an ajax request upon page load to fetch data from the rails database. Initially, the ajax call successfully retrieves the object during the page load event. However, when I attempt to retrieve ...

Guide to Performing Integration Tests on (AngularJS) Web Applications

I'm currently in the process of developing a Webapp that consists of two main parts: a node rest server and an angularjs client. The structure of the app is as follows: Rest Server <--> Api Module <--> Angular App At the moment, the serv ...

JavaScript Countdown Timer Programming

I've scoured countless resources, but most of them only provide code for counting down to a specific day. I'm reaching out in the hopes that someone can assist me by crafting some JavaScript for the following HTML structure. This section of my w ...

Generate customizable additional rows for a table

My current project involves adding details to a database through the use of AJAX and dynamically updating table rows. For example: ---- {Customer: dropdown menu} | {Description: textarea} | delete Add New Customer --- When the user clicks, a drop-d ...

Trigger the event only when the image is updated

I have a requirement to trigger an event only when the image changes after uploading a file. The code I have written below is firing the event not only on image change but also on page load. I want to prevent the event from firing on page load. How can I ...

"Move" Item to the End of an Associative Array Within a Loop

I am attempting to append values to the end of an associative array. The current structure of the array (containing one object) is as follows: Array ( [0] => Array ( [alert] => Array ( [email] => Test ) ) ) During a query on a MySQL database, I ...

Is it possible to maintain variables across a session with numerous users when utilizing socket.io?

My code structure is designed as follows: //Route Handler that triggers when a user 'creates a session' app.post('/route', async (req, res) => { let var1 = []; let var2 = []; io.on('connection', (socket) => ...

I am looking to showcase a series of icons linked together by connecting lines

I have successfully designed the layout and added icons, but I am facing difficulty in creating connecting lines between them. I attempted to utilize CSS borders and pseudo-elements, yet I cannot achieve the desired outcome. If anyone could offer a CSS-ba ...

Is there a way to prevent the Pace js plugin from running on page load, but still have it execute during Ajax requests only?

I have successfully implemented the jquery pace plugin with a progress bar theme. Everything is working well, but I am looking to make it run only on ajax requests. I have tried various solutions found through research, but haven't had any luck. Belo ...

Invoke ajax to reset session once user navigates away from page

I am looking for a solution to automatically clear the PHP session array every time a user exits my webpage. However, I need to exclude cases where the user clicks on links with query strings. I attempted using Javascript code, but it did not work as expec ...

Issue with updating Angular list reference when deleting an item

My current task involves implementing a feature that displays selected items from a hierarchical structure on the right side. slice.component.ts : import { Component, Input, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core&a ...