You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

纯JavaScript实现文件名按类型分类 无匹配项归入通用分组方法

JavaScript文件名分类功能实现

实现逻辑如下:

  • 初始化和types数组对应的分组容器,每个类型对应一个空数组存储匹配的文件
  • 遍历所有文件,优先匹配general之外的类型,匹配到对应特征串就归入对应分组,未匹配到任何类型的归入general分组
  • 每个分组内的文件按name字段做字典序升序排列
  • 按照types数组的给定顺序,将所有分组的内容依次拼接得到最终结果
function sortAndGroupFiles(types, files) {
  // 初始化分组对象
  const groups = Object.fromEntries(types.map(type => [type, []]));

  // 给文件分配对应分组
  files.forEach(file => {
    let isMatched = false;
    // 跳过general,先匹配其他指定类型
    for (let i = 1; i < types.length; i++) {
      const currentType = types[i];
      if (file.name.includes(`-t_${currentType}_t-`)) {
        groups[currentType].push(file);
        isMatched = true;
        break;
      }
    }
    // 未匹配到则归入general分组
    if (!isMatched) {
      groups.general.push(file);
    }
  });

  // 每个分组内按文件名升序排列
  Object.values(groups).forEach(group => {
    group.sort((a, b) => a.name.localeCompare(b.name));
  });

  // 按types指定顺序拼接结果
  return types.flatMap(type => groups[type]);
}

// 示例测试
const types = ["general","picture","document","annotation"];
const files = [
  {name:"-t_picture_t-my_vacation.jpg"},
  {name:"-t_document_t-my_curriculum.pdf"},
  {name:"my_favorite_music.mp3"},
  {name:"my_dance_video.mp4"},
  {name:"-t_annotation_t-dont_forget.txt"},
];

console.log(sortAndGroupFiles(types, files));

内容的提问来源于stack exchange,提问作者Jack Torres

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:54:03