简体   繁体   English

Javascript 数组排序规则字符串和数字字符串

[英]Javascript array sort for regular strings and strings of numbers

I have an array that could be either just a list of strings or it could be just a list of strings of numbers, ie array could be like below我有一个数组,它可能只是一个字符串列表,也可能只是一个数字字符串列表,即数组可能如下所示

let array = ['abc','def','aef','gfh']
             or
let array = ['123','456','192','412']

I want to have sort function that can handle the natural sort in either of these case, below code doesn't seem to handle the string of numbers, is there a way to handle this?我想要排序 function 可以在这两种情况下处理自然排序,下面的代码似乎不能处理数字字符串,有没有办法处理这个?

    array.sort((a,b) => {
        if(a > b) return 1;
        if(a < b) return -1;
        return 0;
    });

You can check whether the element in the array is a number or a string in the sort function.您可以在sort function 中检查array中的元素是数字还是字符串。

The isNaN(string) check would tell you if it is not a number: isNaN(string)检查会告诉您它是否不是数字:

 function sortNumOrStr(array) { return array.sort((a, b) => isNaN(a)? a.localeCompare(b): +a - b); } let array = ['abc', 'def', 'aef', 'gfh'] console.log(sortNumOrStr(array)); array = ['123', '456', '-90', '192', '412']; console.log(sortNumOrStr(array));

You can do this using String#localeCompare() method like:您可以使用String#localeCompare()方法执行此操作,例如:

 let array = ['abc', 'def', 'aef', 'gfh'] array.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })); console.log(array) array = ['123', '456', '192', '412', '5'] array.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })); console.log(array)
 .as-console-wrapper { max-height: 100%;important: top; 0; }

As mentioned in the docs , for numeric sorting we just need to use {numeric: true} option.文档中所述,对于数字排序,我们只需要使用{numeric: true}选项。

 // by default, "2" > "10" console.log(["2", "10"].sort((a,b) => a.localeCompare(b))); // ["10", "2"] // numeric using options: console.log(["2", "10"].sort((a,b) => a.localeCompare(b, undefined, {numeric: true}))); // ["2", "10"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM