筛选路径数组以仅保留最浅的路径
Filter array of paths to keep only the shallowest paths
给定一个随机排序的路径数组,我想过滤它,以便只有最浅的路径保留在数组中。应删除任何子路径。
我在下面的尝试确实过滤了一些路径,但最终结果是错误的,应该是一个只包含这些路径的数组:
[ '/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;
});
});
相关文章:
- 分派点击事件并保留击键修饰符
- Javascript:使用绝对路径设置img src
- 如何在d3.js中返回路径的y坐标
- 如何使用jquery强制一个单词更改大小写等以保留品牌
- 提交后保留下拉选择的值
- 复制图像路径以单击它
- 从模块内部访问Express装载路径
- JS文件的路径正在消失
- 刷新后保留对网页的更改
- 在mvc应用程序中,在回发时保留最初隐藏的文本框的隐藏或可见状态
- 使用onclick绘制SVG路径
- jpm的默认Firefox路径没有'不起作用
- Flash Uploadify在调用我的MVC控制器时没有保留会话/授权
- 筛选路径数组以仅保留最浅的路径
- 错误'路径保留冲突'同时启动流星应用程序
- 删除完整路径,只保留文件名
- r.js优化没有保留路径
- 重新定义window.console函数时,请保留原始路径位置
- Javascript重定向-保留路径和变量,切换域
- 使用grunt和processshtml来更新base href(不保留部分路径)