list.js icon indicating copy to clipboard operation
list.js copied to clipboard

Not sorting negative numbers correctly. Reproduced on listjs.com

Open ghost opened this issue 6 years ago • 5 comments

Hello, listjs is not sorting negative numbers correctly. You can reproduce the code on your own website. Take a look at: http://listjs.com/examples/add-get-remove/

Click "Age" column. As you can see it goes from -23 -> -132 -> 26.

This is wrong, since -132 is smaller than -23, it should be going -132 -> -23 -> 26, etc.

ghost avatar Nov 04 '17 09:11 ghost

I've changed account. This is my account now. Issue is still present.

r3faat1 avatar Nov 14 '17 01:11 r3faat1

Hello, I've figured this out. I resolved the problem by creating my own sort function and telling ListJS to use that. Below is the code that works for ME, but may not for you. So modify it as necessary.

        function listJSCustomNumericSort(a, b)
        {
            var before = parseFloat(a._values.profit.replace(/[^0-9.-]/g, ""));
            var after = parseFloat(b._values.profit.replace(/[^0-9.-]/g, ""));

            if (before > after) { return 1; }
            if (before < after) { return -1; }
            else { return 0; }
        }

        tableLJS.sort('profit', { sortFunction: lisJSCustomNumericSort, order: sortOrder });

Feel free to close this out, I wasn't sure if anybody else wanted to look at it first. Thanks.

r3faat1 avatar Nov 23 '17 23:11 r3faat1

@r3faat1

I am having this exact problem in 2022, and can't get your code to work. Could you help?

In the code above, sortOrder is not defined. Do you simply replace it with "asc" or "desc"? And why would you want to define this at all? The user needs to be able to choose either asc or desc, and does this not fix the sort order?

What does "return 1", "return -1" and "return 0" mean? Are you just using "return 1" for "return: true"? I have never seen "return -1" before, so don't understand this.

Finally, the values below are what I console.log out from "before" and "after" when running the code on a table with these values: [1.71, -3.95, -2.09, 3.39, 12.36, -1.28]. Any idea what's happening:

before: NaN after: 1.71 before: -3.95 after: NaN before: NaN after: -3.95 before: -2.09 after: NaN before: NaN after: -2.09 before: 3.39 after: NaN before: NaN after: 3.39 before: 12.36 after: NaN before: NaN after: 12.36 before: -1.28 after: NaN before: NaN after: -1.28

Would very much appreciate some pointers. Cheers.

Vemb avatar Sep 09 '22 16:09 Vemb