过滤路径数组以仅保留最浅路径

时间:2015-03-12 19:55:31

标签: javascript arrays

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

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

[ '/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;
});

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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

以下是我刚刚提出的解决方案:

paths.filter(function (path) {
  return paths.every(function (another) {
     return another === path || path.indexOf(another) !== 0;
  });
});