LoginSignup
0
0

More than 5 years have passed since last update.

javascriptでファイル名の配列を拡張子順に並べ替える

Last updated at Posted at 2017-06-06

昇順

const sortFiles = (list) => { //list = ["src/index.text", "src/index.html"]
  list.sort(function(a,b){
    var aExtension = a.split('.')[1]
    var bExtension = b.split('.')[1]
    if( aExtension > bExtension ) return 1;
    if( aExtension < bExtension ) return -1;
    return 0;
  });

結果:["src/index.html", "src/index.text"]

降順にするには1-1を逆にする。

追記

@yama-ts さんより)上の方法だとindex.min.cssのような場合うまく行かないので、最後のピリオドを見るようにする。


const sortFiles = (list) => { //list = ["src/index.text", "src/index.html"]
  list.sort(function(a,b){
    const reg = /\.[^\.]+$/;
    const aExtension = a.match(reg);
    const bExtension = b.match(reg);
    if( aExtension > bExtension ) return 1;
    if( aExtension < bExtension ) return -1;
    return 0;
  });
};
0
0
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0