javascript - 排序以字母开头的数组字符串

标签 javascript node.js sorting node-webkit

我如何对这个数组列表进行排序以确保所有以 _ 开头的文件排在第一位?

上下文:用于加载程序,我想确保首先使用 _ 加载所有文件。

列表是通过扫描随机生成的,所以我永远无法确定顺序。

0:"js\game\global\app.js"
1:"js\game\global\camera.js"
2:"js\game\global\displayGroups.js"
3:"js\game\global\dataBase.js"
4:"js\game\global\mouse.js"
5:"js\game\global\loaders.js"
6:"js\game\global\stage.js"
7:"js\game\global\polyfill.js"
8:"js\game\scenes\scene_boot.js"
9:"js\game\scenes\scene_IntroVideo.js"
10:"js\game\scenes\scene_loader.js"
11:"js\game\scenes\scene_Map1.js"
12:"js\game\scenes\_scene_base.js" //need to be alway first
13:"js\game\scenes\scene_Title.js"

所以在这个例子中,排序之后,文件_scene_base应该排在第一位。

这是我的测试代码,但它显示不稳定,我不知道为什么,有时它不起作用。

 files.sort((a,b) => {return a.indexOf("\_")>-1?-files.indexOf(a):0 });

对不起,如果我的英语很差。

最佳答案

另一种基于indexOf 且仅下划线第一位的解决方案。

const arr = [
  'js\\game\\global\\app.js',
  'js\\game\\global\\camera.js',
  'js\\game\\global\\displayGroups.js',
  'js\\game\\global\\dataBase.js',
  'js\\game\\global\\mouse.js',
  'js\\game\\global\\loaders.js',
  'js\\game\\global\\stage.js',
  'js\\game\\global\\polyfill.js',
  'js\\game\\scenes\\scene_boot.js',
  'js\\game\\scenes\\scene_IntroVideo.js',
  'js\\game\\scenes\\scene_loader.js',
  'js\\game\\scenes\\scene_Map1.js',
  'js\\game\\scenes\\scene_Title.js',
  'js\\game\\scenes\\_scene_base.js',
  'js\\game\\scenes\\scene_Loader.js',
  'js\\game\\scenes\\_scenebase.js',
  'js\\game\\scenes\\sceneTit_le.js',
  'js\\game\\scenes\\scene_introVide_o.js',
  'js\\game\\scenes\\sceneIntroVi_deo.js',
];

arr.sort((a, b) => {
   const ai = a.indexOf('_');
   const bi = b.indexOf('_');
   return (ai > -1 && bi > -1 && (ai - bi)) || -1;
});

console.log(arr)

关于javascript - 排序以字母开头的数组字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56611426/

相关文章:

javascript - 该 Node/es6 代码的输出是什么?为什么?

javascript - 如何测试expressJS Controller -NodeJS

java - 排序列表后,如何将列表中的对象取回它们原来的位置?

linux - bash - 根据从文件名中提取的信息 move 文件

javascript - Jquery 不能与 ajax 一起工作?

javascript - 随着时间的推移,使用 Node.js 写入磁盘会变慢

node.js - 在 MongoDB 中分区数据的最佳实践是什么?

powershell - 自定义Powershell排序功能

javascript - 如何忽略 typescript 中的 "Cannot find name ' M'“错误?

javascript - 仅当输入字段中有内容时才使用 javascript 分配类