筛选路径数组以仅保留最浅的路径

Filter array of paths to keep only the shallowest paths

本文关键字:路径 保留 数组 筛选      更新时间:2023-09-26

给定一个随机排序的路径数组,我想过滤它,以便只有最浅的路径保留在数组中。应删除任何子路径。

我在下面的尝试确实过滤了一些路径,但最终结果是错误的,应该是一个只包含这些路径的数组:

[ '/video', '/audio', '/code', '/images', '/test/noparent' ]

var paths = [
  '/code/client/images',
  '/code/client/templates/views',
  '/code/another/templates/views',
  '/code/client/svg',
  '/images',
  '/code/another',
  '/code/client',
  '/audio/asdasd',
  '/audio/asd',
  '/code/client/html',
  '/video',
  '/code/client/templates',
  '/audio/asd/asdasd',
  '/code/another/html',
  '/code/another/images',
  '/code/another/svg',
  '/code/another/templates',
  '/code',
  '/audio',
  '/test/noparent'
];
// prepare by sorting paths by number of slashes
paths.sort(function (a, b) {
  return a.match(/'//g).length - b.match(/'//g).length;
});
// filter (this fails)
paths.filter(function (path) {
  var keep = true;
  paths.forEach(function (another) {
      if (another.indexOf(path) === 0 && another !== path) keep = false;
  });
  return keep;
});

也许有一个解决方案不会迭代多次?

您需要反转字符串的存在。检查当前路径是否是没有其他路径适合的路径(indexOf)。

paths.filter(function (path) {
  var keep = true;
  paths.forEach(function (another) {
      if (path.indexOf(another) === 0 && another !== path) keep = false;
  });
  return keep;
});

这是我刚刚

露营的解决方案:
paths.filter(function (path) {
  return paths.every(function (another) {
     return another === path || path.indexOf(another) !== 0;
  });
});