Search code examples
bootstrap-table

Sorting numbers containing commas


I am trying to sort a column of numbers using commas, eg 1,092,021. The sorting is treating the , as a decimal and sorting improperly. eg:

1,330,000
2,350,000
3
5
7,000,000
etc

Is there a way to get the comma separated numbers to sort properly?


Solution

  • Here is the solution @JaredT proposed:

    var nums = ['1,330,000', '2,350,000', '3', '5', '7,000,000', '1,000', '100'];
    
    nums
        .map(function (n) { return parseInt(n.replace(/,/g, ''));})
        .sort(function (a, b) { return a > b;})
        .map(function (i) {
            return String(i).split('')
                .reverse()
                .map(function (n, i) {
                    return n + (!i || (i % 3) ? '' : ',');
                })
                .reverse()
                .join('');
        });