如何在JavaScript中对按顺序编号的文件进行排序?

时间:2018-06-09 23:09:12

标签: javascript

我的文件名如下:

X-1.pdf
X-2.pdf
X-3.pdf
.
.
.
X-15.pdf

根据字符串值排序时,顺序如下:

X-1.pdf
X-10.pdf
X-11.pdf
.
.
.

假设这些文件存储在一个字符串数组中,我如何订购该数组,以便文件显示在预期的'方式即

X-1.pdf
X-2.pdf
.
.
.

2 个答案:

答案 0 :(得分:2)

您可以localeComparenumeric选项设置为true时使用console.log( ['X-11.pdf', 'X-1.pdf', 'X-9.pdf', 'X-10.pdf', 'X-2.pdf', ].sort((a, b) => a.localeCompare(b, 'en', {numeric: true })) )

use nom::types::CompleteStr;

use nom::*;

named!(csv_style_string<CompleteStr, String>,
    delimited!(
        char!('"'),
        map!(
            many0!(
                alt!(
                    // Eat a " delimiter and  the " that follows it
                    tag!("\"\"") => { |_| '"' }

                |    // Normal character
                    none_of!("\"")
                )
            ),
             // Make a string from a vector of chars
            |v| v.iter().collect::<String>()
        ),
        char!('"')
    )
);

fn main() {
    println!(r#""Alo\"ha" = {:?}"#, csv_style_string(CompleteStr(r#""Alo""ha""#)));
    println!(r#""" = {:?}"#, csv_style_string(CompleteStr(r#""""#)));
    println!(r#"bad format: {:?}"#, csv_style_string(CompleteStr(r#""A""" e""#)));
}

答案 1 :(得分:-1)

我认为最好的方法是删除字母字符,然后按这种方式排序。

&#13;
&#13;
const files = ['X-1.pdf', 'X-10.pdf', 'X-2.pdf', 'X-3.pdf', 'X-4.pdf', 'X-11.pdf', 'X-5.pdf', 'X-6.pdf', 'X-8.pdf', 'X-9.pdf', 'X-12.pdf', 'X-13.pdf', 'X-14.pdf', 'X-15.pdf', 'X-7.pdf']

files.sort((a, b) => parseInt(b.replace(/[^0-9]/, '')) - parseInt(a.replace(/[^0-9]/, '')))

console.log(files)
&#13;
&#13;
&#13;