lorenzofox3 / Smart-Table

Code source of Smart Table module: a table/grid for Angularjs
http://lorenzofox3.github.io/smart-table-website/
1.8k stars 513 forks source link

Natural sort of alpha numeric string #826

Closed golf-x closed 6 years ago

golf-x commented 6 years ago

https://stackoverflow.com/questions/2802341/javascript-natural-sort-of-alphanumerical-strings

Is there any way to sort by alpha numeric string like in the above Stackoverflow post, but I can't find any way on how to do this.

AngularJs version - 1.5.2 Smart table version - 2.1.10

I find someone mention about "st-set-sort" somewhere but it is not in the documentation.

golf-x commented 6 years ago

https://github.com/lorenzofox3/Smart-Table/blob/8047db0722f59f52669ca28b34520f0999914d59/src/stTable.js

There is a code here even though there is no documentation

I can figure it out now, there is no documentation on this this is the directive to use

(function() { 'use strict';

angular
    .module('tatooineApp')
    .filter('naturalsort', function() {
        return function(items, field, isDescending){

            //If you don't create a copy of the array, 
            //smart-table won't be able to restore the natural order state
            var result = items.slice();

            //Working only for string properties ATM!
            result.sort(function(first, second){
              //return first.a.localeCompare(second.a, 'tr');
              //OR
              return first[field].localeCompare(second[field], undefined, {numeric: true, sensitivity: 'base'});

              //localCompare() is supported only in IE11 and upwards
            });

            if (isDescending){
              result.reverse();
            }

            return result;

          };
    })

})();