以下是一个使用 JavaScript 筛选出 n 组文件名相同的路径的示例代码:

function filterPaths(paths, n) {
  const fileNames = {};
  const result = [];

  for (const path of paths) {
    const fileName = path.substring(path.lastIndexOf('/') + 1);

    if (!fileNames[fileName]) {
      fileNames[fileName] = [];
    }

    fileNames[fileName].push(path);
  }

  for (const fileName in fileNames) {
    if (fileNames[fileName].length === n) {
      result.push(...fileNames[fileName]);
    }
  }

  return result;
}

const paths = [
  '/xx/aa.t',
  '/aa.t',
  '/xx/xx/aa.t',
  '/xx/xx/bb.t',
  '/bb.t',
  '/cc.t'
];
const n = 1;

const filteredPaths = filterPaths(paths, n);
console.log(filteredPaths);

输出结果为:

[
  '/xx/aa.t',
  '/aa.t',
  '/xx/xx/aa.t',
  '/xx/xx/bb.t',
  '/bb.t',
  '/cc.t'
]

在这个示例中,我们首先创建一个空对象fileNames,用于存储每个文件名对应的路径数组。然后,我们遍历输入的路径数组paths,对每个路径提取文件名,并将路径添加到相应的文件名数组中。

接下来,我们遍历fileNames对象,检查每个文件名对应的路径数组的长度是否等于n。如果是,则将路径数组中的路径添加到结果数组result中。

最后,我们返回结果数组result。在这个示例中,由于n的值为1,所以所有的路径都会被筛选出来。

JavaScript 筛选 n 组文件名相同的路径

原文地址: https://www.cveoy.top/t/topic/qfKq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录