Sort Array Elements (string with numbers), natural sort

后端 未结 8 1109
你的背包
你的背包 2020-11-22 10:15

I have an array like;

[\"IL0 Foo\", \"PI0 Bar\", \"IL10 Baz\", \"IL3 Bob says hello\"]

And need to sort it so it appears like;



        
8条回答
  •  醉话见心
    2020-11-22 10:28

    You could use String#localeCompare with options

    sensitivity

    Which differences in the strings should lead to non-zero result values. Possible values are:

    • "base": Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.
    • "accent": Only strings that differ in base letters or accents and other diacritic marks compare as unequal. Examples: a ≠ b, a ≠ á, a = A.
    • "case": Only strings that differ in base letters or case compare as unequal. Examples: a ≠ b, a = á, a ≠ A.
    • "variant": Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. Other differences may also be taken into consideration. Examples: a ≠ b, a ≠ á, a ≠ A.

    The default is "variant" for usage "sort"; it's locale dependent for usage "search".

    numeric

    Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are true and false; the default is false. This option can be set through an options property or through a Unicode extension key; if both are provided, the options property takes precedence. Implementations are not required to support this property.

    var array = ["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"];
    
    array.sort(function (a,b) {
        return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
    });
    
    console.log(array);

提交回复
热议问题