List.js - Problem sorting by price (numbers with comma and dot)

1.4k views Asked by At

I've built a site for a local bike store I visit frequently, I'm currently hosting a non-live version at http://mattgreenfield.co.uk/bikestore/store.html.

I've just installed the brilliant list.js (http://listjs.com) to enable the store page to sort and filter (the owner does not wish to sell products online but to get customers phoning up and visiting the brick and mortar store).

It seems to work pretty well but the sort by price button doesn't seem to be sorting by price, the values should be sorting high to low but are not. Would this be anything to do with it only sorting by the first digit of the number possibly? £4000 seems to be sorted as less that £479 for example - the first digit is the same but 7 is more than 0 (second digit).

I may have missed something simple as the original example from where I copied the code was sorted by year, years only ever have 4 digits so this problem would not occur.

2

There are 2 answers

1
max On BEST ANSWER

£3,799.99 is not really a number. Although we humans can easily disregard the comma and pound sign computers are not as smart. The solutions is to replace list.js`s internal values with a sortable floating point number.

// loop through the list
$.each(userList.items, function(k, item){
    var val = item._values; 
    // this strips anything that is not a dot or digit
    var price = item._values.price.replace(/[^\d\.]/g,"");
    item._values.price = parseFloat(price); 
});
0
Alessio On

A new solution came up into List.js Github, using List.js version 1.5.0:

You can define a custom data-attribute with the plain value (no comma and using the dot for decimals).

<td class="name">Random Name</td>    
<td class="price" data-price="12345.00">$12,345.00</td>

And you have to make some small changes to the options array, as follow:

<script type="text/javascript">
    var sortableClassValues = [
        "name",
        { name: 'price', attr: 'data-price' }
    ]

    var listOptions = {
        valueNames: sortableClassValues
    };

    var myList = new List('table_ID', listOptions);
</script>

If then you want to have a default sorting, you can add, after initializing the List:

myList.sort("price", {
    order: "desc"
});

Here's a working example, linked from Github: https://kanaxx.github.io/listjs/number-sort.html