gpt4 book ai didi

javascript - 减少数组列表,以设置公共(public)路径

转载 作者:行者123 更新时间:2023-11-30 14:30:37 24 4
gpt4 key购买 nike

我正在尝试将列表缩减为更短的列表,仅包含常见的文件系统路径。试图找到所有共同的祖 parent ,并只将那些放在最终列表中。以下是目标:目标是我们必须消除列表中存在父目录的所有目录。

更好的表达方式可能是:目标是我们必须消除列表中存在该路径父目录的所有路径。

假设我有这样的输入和预期的输出:

const input = [
"/home/oleg/WebstormProjects/oresoftware/r2g",
"/home/oleg/WebstormProjects/oresoftware/sumanjs/suman",
"/home/oleg/WebstormProjects/oresoftware/sumanjs",
"/home/oleg/WebstormProjects/oresoftware/sumanjs/suman-types",
"/home/oleg/WebstormProjects/oresoftware/sumanjs/suman-watch"
];

const output = [
"/home/oleg/WebstormProjects/oresoftware/r2g",
"/home/oleg/WebstormProjects/oresoftware/sumanjs",
];

const getReducedList = function (input) {

return input
.sort((a, b) => (a.length - b.length))
.reduce((a, b) => {

// console.log('a:', a, 'b:', b);

const s = !a.some(v => {
return b.startsWith(v);
});

if (s) {
a.push(b);
}

return a;

}, []);

};

console.log(getReducedList(input));

那个getReducedList函数似乎适用于我们的第一个测试用例,5 减少到 2。但是,如果我们添加第二个测试用例,事情就会变得奇怪:

如果我从原始列表中删除一个项目并将其更改为这个包含 4 个的列表:

const input = [
"/home/oleg/WebstormProjects/oresoftware/r2g",
"/home/oleg/WebstormProjects/oresoftware/sumanjs/suman",
"/home/oleg/WebstormProjects/oresoftware/sumanjs/suman-types",
"/home/oleg/WebstormProjects/oresoftware/sumanjs/suman-watch"
];

然后我希望得到这个输出(相同的 4 列表):

const output = [
"/home/oleg/WebstormProjects/oresoftware/r2g",
"/home/oleg/WebstormProjects/oresoftware/sumanjs/suman",
"/home/oleg/WebstormProjects/oresoftware/sumanjs/suman-types",
"/home/oleg/WebstormProjects/oresoftware/sumanjs/suman-watch"
];

我期望/想要相同的 4 列表的原因是因为列表中的任何项目都没有列表其他地方的父目录。但我实际上得到了这个输出,一个 2 的列表,这是不正确的:

const output =  [ 
'/home/oleg/WebstormProjects/oresoftware/r2g',
'/home/oleg/WebstormProjects/oresoftware/sumanjs/suman'
];

有谁知道我该如何解决这个问题以获得预期的结果?答案需要满足两个测试用例。

为了清楚起见,如果您添加 "/home/oleg"到原始列表,然后"/home/oleg"应该是输出中的唯一条目。

最佳答案

我想你可以用一个非常简单的递归函数来做到这一点。您只需按长度排序,然后递归弹出最短的,将其添加到结果中,用它过滤数组,递归:

const input = [
"/home/oleg/WebstormProjects/oresoftware/r2g",
"/home/oleg/WebstormProjects/oresoftware/sumanjs/suman",
"/home/oleg/WebstormProjects/oresoftware/sumanjs",
"/home/oleg/WebstormProjects/oresoftware/sumanjs/suman-types",
"/home/oleg/WebstormProjects/oresoftware/sumanjs/suman-watch"
];

input.sort((a,b) => b.length - a.length)
function getPrefixes(list, res =[]) {
if (list.length < 1) return res
let next = list.pop()
res.push(next)
return getPrefixes(list.filter(u => !u.startsWith(next + '/')), res)

}
console.log(getPrefixes(input))

关于javascript - 减少数组列表,以设置公共(public)路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51240757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com