Javascript function to compare two thousands separator number not working

I’m trying to write a comparator function in javascript which compares two numbers like '100,000', '200,000' etc. and returns their difference. I want to use this in the ag-grid’s inbuilt custom sorting by ‘comparator‘ functionality provided here for the Date column: https://www.ag-grid.com/javascript-grid-sorting/

My code is like this:

function thousandsComparator(Num1, Num2) {
    var Number1 = thousandsToComparableNumber(Num1);
    var Number2 = thousandsToComparableNumber(Num2);

    if (Number1===null && Number2===null) {
        return 0;
    }
    if (Number1===null) {
        return -1;
    }
    if (Number2===null) {
        return 1;
    }

    return Number1 - Number2;
}

function thousandsToComparableNumber(num) {
    var total = parseFloat(num.replace(/,/g, ''));
    return total;

}

But, it’s not working. It’s not sorting the column! –> {headerName: "ORDER Qty", field: "ORDER_QTY", width: 150, comparator: thousandsComparator, unSortIcon: true, cellStyle:{"text-align":"right"}},

The column data is like this “100,000”, “200,000” etc.

Answer

Looking at your plunker you’re dateComparator which as it stands doesn’t take commas into account. You are have date1, date2) as arguments to dateComparator, but use date1Number/date2Number within.

You need to change dateComparator to:

function dateComparator(date1Number, date2Number) {

    if (date1Number === null && date2Number === null) {
        return 0;
    }
    if (date1Number === null) {
        return -1;
    }
    if (date2Number === null) {
        return 1;
    }

    return thousandsToComparableNumber(date1Number) - thousandsToComparableNumber(date2Number);
}

This will fix your problem, but a better solution would be to leave the data in its raw state and use a cellRenderer to have commas as seperators.

In other words, remove the dateComparator altogether, and have the following for your colDef:

{
    headerName: "ORDER Qty", 
    field: "ORDER_QTY", 
    width: 150, 
    cellStyle: {
        "text-align": "right"
    },
    cellRenderer: function (params) {
        return Number(params.value).toLocaleString();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *