javascript - 如何按字典顺序和数字顺序对一组数字进行排序?

标签 javascript sorting extjs lexicographic

我目前有一组字符串,它们都是数字和带有 + 或 - 的数字。如下:

1 , 1+, 1-, 2, 2+, 2-, 10

当我使用 JavaScript 的排序函数进行排序时,会给出:

1, 1+, 1-, 10, 2, 2+, 2-

这是按字典顺序而不是数字顺序。有没有办法对此进行排序,以便数字以正确的方式(第一个列表)出现?我正在使用 ExtJS 商店,所以作为商店分类器的答案是首选,但普通的 javascript 也很好。谢谢?

编辑:这不仅仅是排序数字。

最佳答案

您可以像这样使用自定义排序函数:

var numbers = ['1', '1-', '1+', '2', '2+', '2-', '10'];

numbers.sort(function (a, b){
    var _a = parseFloat(a), // If the values are integers only, parseInt will do too
        _b = parseFloat(b);
    if (_a - _b === 0) {
    	return (a > b) ? 1 : -1;
    } else {
    	return _a - _b;
    }
});

console.log(numbers);

该函数检查数字值是否相等,如果相等,则退回到字典顺序对字符后缀进行排序。如果相等大小写中没有后缀,则无论返回数字的顺序如何。如果只有一个操作数有后缀,则 bare number 返回负数。如果数字值不相等,该函数只返回三态,即 a - b,它将被评估为 negative, 0, positive 之一。或者实际上它是“双态”,因为我们已经处理了 0 案例。


更通用的解决方案

上面的代码只是两个不同的单字符后缀的特例。如果后缀更复杂,这里有一个更通用的代码来按数字和后缀排序:

var numbers = ['1', '1-r', '1+q', '1', '2', '2+q', '2-r', '10'];
function suffixSort (suff, asc) {
    asc = 2 * +(!!asc) - 1; // Convert boolean to -1 or 1
    return function (a, b) {
        var _a = parseFloat(a), // Extract the number value
            _b = parseFloat(b),
            aSI = -(a.length - _a.toString().length), // Get the index of suffix start
            bSI = -(b.length - _b.toString().length);
        // Equal number values, sort by suffixes
        if (_a === _b) {
            return (suff.indexOf(a.substr(aSI)) > suff.indexOf(b.substr(bSI))) ? 1 : -1;
        }
        // Inequal number values, sort by numbers
        return asc * (_a - _b);
    }
}
// suffixSort arguments
//   suff: An array of the suffix strings to sort, ordered in the desired sorting order
//   asc:  true = ascending, false = descending. Optional, defaults to descending sort
numbers.sort(suffixSort(['+q', '-r'], true));
console.log(numbers);

想法是将后缀存储到一个数组中,当需要对后缀进行排序时,函数比较后缀的数组索引而不是后缀本身。

suffixSort 还可以让您决定排序方向。选择的排序方向对后缀排序没有影响,它们总是按照它们在 suff 数组中出现的顺序返回。

关于javascript - 如何按字典顺序和数字顺序对一组数字进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40049538/

相关文章:

javascript - 如何使用 webpack 配置 pm2 以进行 typescript 编译和重新加载?

algorithm - 以最少的步数对数组进行排序

java - 如何对 map 列表进行二次排序

javascript - 如何拆分绑定(bind)字符串 ExtJS

javascript - 高级选项卡面板向导

javascript - orientjs 的基本问题故障排除(node.js 的 OrientDB 驱动程序)

Javascript - 循环遍历数组

javascript - 如何编辑单个页面的 css 及其元素(wordpress)?

list - Backbone Marionette CompositeView 排序列表 - 在添加时呈现额外的模型

javascript - Sencha touch 2 Ext.factory范围