user888750
user888750

Reputation:

localCompare for Integers

I'm using localCompare to compare some strings, those strings are numbers. I want the order to be numeric. How can I do this?

Sort function:

requestAmountEl.find('optgroup').each(function(){
    var $this = jQuery(this);

    options = $this.children('option');
    options.detach().sort(function(a,b) {
        return b.value.localeCompare(a.value);
    }).appendTo($this);
});

Result:

<optgroup label="6 Months">
    <option value="2000">$2,000</option>
    <option value="11000">$11,000</option>
    <option value="10000">$10,000</option>
    <option value="1000">$1,000</option>
</optgroup>

Right now it'll sort 2000, 10000, 11000, 1000.

Upvotes: 2

Views: 6981

Answers (3)

Kamo Petrosyan
Kamo Petrosyan

Reputation: 234

For my code when dynamic sort field/attribute selected (name as string or id as integer or value any or etc...) works this universal solution

sortedCategories() {
    return [...this.categories].sort((cat1, cat2) => {
        return cat1[this.selectedSort]?.toString().localeCompare(cat2[this.selectedSort].toString());
    });
},

So try in Your code

requestAmountEl.find('optgroup').each(function(){
    var $this = jQuery(this);

    options = $this.children('option');
    options.detach().sort(function(a, b) {
        return b.value?.toString().localeCompare(a.value.toString());
    }).appendTo($this);
});

Upvotes: 0

pomo
pomo

Reputation: 2301

String.localeCompare has what you need. Pass in the numeric option and it will treat your strings as numbers:

['2000', '11000', '10000', '1000'].sort(
  (a, b) => a.localeCompare(b, undefined, {'numeric': true})
);

... results in:

["1000", "2000", "10000", "11000"]

Upvotes: 8

user888750
user888750

Reputation:

Solution:

requestAmountEl.find('optgroup').each(function(){
    var $this = jQuery(this);

    options = $this.children('option');
    options.detach().sort(function(a,b) {
        if (parseInt(b.value) > parseInt(a.value)) return 1;
        else if (parseInt(b.value) < parseInt(a.value)) return -1;
        else return 0;
    }).appendTo($this);
});

Upvotes: 3

Related Questions