Sorting arrays encounters an issue where objects lacking a certain property are placed at the beginning

Below is an example of my object array:

let plans = [
{
    surf: 5,
    price: 299,
    cprice: 199,
    cdur: 3,
},
{
    surf: 5,
    price: 249,
    cprice: 199,
    cdur: 3,
},
{
    surf: 15,
    price: 149,
    cprice: "",
    cdur: "",
},
];

In order to sort this array, I've implemented the following comparisons:

function cpriceDesc( a, b ) {
    if ( a.cprice < b.cprice ){
        return -1;
    }
    if ( a.cprice > b.cprice ){
        return 1;
    }
    return 0;
}

function cpriceAsc( a, b ) {
    if ( a.cprice > b.cprice ){
        return -1;
    }
    if ( a.cprice < b.cprice ){
        return 1;
    }
    return 0;
}

While sorting works correctly for objects with a cprice value, those without one always end up at the beginning of the sorted array. How can I ensure that they are placed at the end instead?

Answer №1

If you want to differentiate normal numbers from other types, such as strings, you can utilize the Number.isFinite method.

Consider simplifying your current sorting callback functions by using subtraction, like return a.cprice - b.cprice. To implement the distinction mentioned above, you can adjust the subtraction operation like this:

Number.isFinite(b.cprice) - Number.isFinite(a.cprice)
. When this results in 0 (indicating they belong to the same "category"), proceed with the original a.cprice - b.cprice subtraction (or its reverse).

const plans = [{surf: 5,price: 299,cprice: 199,cdur: 3,},{surf: 5,price: 249,cprice: 199,cdur: 3,},{surf: 15,price: 149,cprice: "",cdur: "",},];

const sortAsc = (a, b) => Number.isFinite(b.cprice) - Number.isFinite(a.cprice) || a.cprice - b.cprice;
const sortDesc = (a, b) => Number.isFinite(b.cprice) - Number.isFinite(a.cprice) || b.cprice - a.cprice;

console.log(plans.sort(sortDesc));

It's recommended not to define prices as strings when there is no price available. Instead, consider omitting the property altogether. By following this approach, the provided code will still function correctly.

Answer №2

To prioritize values at the bottom, it is advisable to check for empty strings before sorting by the actual value.

let
    plans = [{ surf: 5, price: 14, cprice: "", cdur: "" }, { surf: 5, price: 299, cprice: 198, cdur: 3 }, { surf: 5, price: 249, cprice: 199, cdur: 3 }, { surf: 15, price: 149, cprice: "", cdur: "" }];
    

plans.sort((a, b) =>
    (a.cprice === '') - (b.cprice === '') ||
    a.cprice - b.cprice
);

console.log(plans)
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Encrypting text within a Chrome Extension

Looking for a way to hash values in a Chrome extension specifically using sha256 and ripemd160 with a key. Since PHP can't be used and JavaScript doesn't have a built-in function for this, the only solution I see is either sending a request to a ...

Pattern matching for spaces and quotation marks

Despite reading several tutorials on regular expressions, I am still struggling to create the exact expression I need. I have an onblur function that performs the following actions... var x = $("#outputpathid").val(); var testwhitespace = new RegExp ...

eliminate several digits past the decimal place

I thought this would be a simple task, but I'm completely stuck with the code I currently have! https://i.sstatic.net/Y36Cg.png render: (num) => { return <span><b>{num.toFixed(2)}</b>%</span>; // rounding to two de ...

Remove a data entry from the MySQL database by selecting the corresponding row in the table and utilizing the DELETE function

Is there a way to remove a record from my MySQL database by clicking on a row in a table that is generated using ejs? Below is the code I am currently using to generate the table rows. <% res.forEach(function(item){ %> <tr> ...

leveraging properties to extract data from a dataset

I've been attempting to construct a table using props and then pass the value from that table to another function. However, I am facing an issue where the result is not being displayed. Can you pinpoint what I might have done incorrectly? import Table ...

"Uncovering the Hidden Bug: Memory Leak in Google Maps caused by Map.panTo() Function in Javascript

I've been encountering Javascript Out of Memory errors with a Web App that involves loading a Google Map and continuously panning from one point to another. It typically takes around half a day before memory is depleted, but I'm aiming for much l ...

Maximize performance for jQuery datatables through advanced row grouping techniques

Recently, I started incorporating the jquery datatables plugin into my project and I must say it's quite impressive. However, I encountered a roadblock when attempting to implement row grouping on my own. Unfortunately, my solution is far from optimal ...

The synergy of Redux with scheduled tasks

In order to demonstrate the scenario, I have implemented a use-case using a </video> tag that triggers an action every ~250ms as the playhead moves. Despite not being well-versed in Flux/Redux, I am encountering some challenges: Is this method cons ...

Issue with recurring Window Alerts in Google Apps Script

I'm currently facing an issue with an alert appearing multiple times whenever a function is executed within a Google Apps Script written for a spreadsheet. I believe I've identified the root cause of the problem, but I'm uncertain about the ...

Tips for combining multiple lists into a dropdown menu based on selected checkboxes

Imagine a scenario where there are 5 checkboxes, each with a unique value mapped to a specific list of elements. In my particular case, I have an associative PHP array as shown below: [100] => Array ( [0] => Array ( [name] => NameABC [sid] => ...

Send information to the server using the POST method

Trying to send data on button click using Angular 1.x. Client-side debug shows object set correctly: https://i.sstatic.net/Emjpk.png Server-side debug reveals lost values: https://i.sstatic.net/50l4G.png Here is my POCO: [Serializable] public class I ...

Next.js project encountered a TypeError with message [ERR_INVALID_ARG_TYPE]: The "to" argument is expected to be a string type

While working on a Next.js application, I came across a TypeError that is linked to the undefined "to" argument. This issue pops up when I launch my development server using npm run dev. Despite checking my environment setup and project dependencies, I hav ...

What could be preventing me from successfully calling the JavaScript AJAX function in this particular situation?

Here is my code snippet from a smarty template: <form name="transaction_form" id="transaction_form"> <table class="trnsction_details" width="100%" cellpadding="5" > <tbody> <tr> ...

Error encountered while attempting to login to the Winston Logger in the /var/log directory

After hours of attempts, I am still struggling to get Winston to log in my /var/log directory on my Fedora system. I conducted a test project using Express and found that logging works fine within the project directory. However, when attempting to log any ...

Implementing class attributes in VueJS functional components

Creating a VueJS functional component to emulate div behavior involves setting its class based on the props it receives. For example: <MyDiv textAlign="left">Div with left aligned text</MyDiv> Transforms into: <div class="text-left">Di ...

Top method for locating necessary element within an array of objects

Within my array of objects, each object in the class has a unique name variable. I am looking to locate an object within the array that has the name "test". My initial thought was to create a separate array containing only the names as elements, syncing th ...

Angular is notifying that an unused expression was found where it was expecting an assignment or function call

Currently, I am working on creating a registration form in Angular. My goal is to verify if the User's username exists and then assign that value to the object if it is not null. loadData(data: User) { data.username && (this.registrationD ...

What is the best way to have a JavaScript div display automatically upon loading, but then be hidden when a different div link is clicked

Feel free to check out a sample of my page here: . My goal is to load the MEC div and then close it when clicking on another link, like Minimum Value Plans in the top bar. I experimented with setting it to "display:block" instead of "display:none", but unf ...

Ways to Dynamically Extract Elements from an Array using a Loop

How can I extract the ID from a link that is stored in an array and split by forward slashes? Currently, I am only able to retrieve the main link ID from the array, such as "/4tzCuIpHHhc/long-title-here", but I need to specifically get the ID 4tzCuIpHHhc. ...

"Exploring the best method to utilize a for loop for updating an array of objects in

I'm looking to update a nested mongo document using a for loop with my node.js code below: //loop starts var update = { "rate":mainRate, "classifierCategories."+e+".rate":temiz[i].slice(0,2) }; classifier.update({"classifierS ...