如何过滤以下数组
[ '/pageA/pageAA.html',
'/pageB.html',
'/pageC.html',
'/pageC/',
'/pageC/pageW/pageC.html',
'/' ]
获取
[ '/pageA/pageAA.html',
'/pageB.html',
'/pageC/pageW/pageC.html' ]
规则是:
/
结尾/
结尾的另一条路径相似,例如:'/pageC/'
和'/pageC.html'
相似我已经完成了以下工作,但它并不干净,也许使用正则表达式或类似的东西会有更简洁的方式
const routes = ['/pageA/pageAA.html',
'/pageB.html',
'/pageC.html',
'/pageC/',
'/pageC/pageW/pageC.html',
'/'
]
const filterRoutes = routes => {
var unWontedRoutes = []
for (let i = 0; i < routes.length - 1; i++) {
for (let j = i + 1; j < routes.length; j++) {
if (Math.abs(routes[i].length - routes[j].length) == 4) {
var a = routes[i].length < routes[j].length ? routes[j] : routes[i]
var b = routes[i].length > routes[j].length ? routes[j] : routes[i]
if (a.replace(b.slice(0, b.length - 1), '') === '.html') {
unWontedRoutes.push(a)
}
}
}
}
return unWontedRoutes
}
const unWontedRoutes = filterRoutes(routes)
const newRoutes = routes.filter(route => (!(unWontedRoutes.indexOf(route) > -1) && !route.endsWith('/')))
console.log(newRoutes)
答案 0 :(得分:1)
您可以使用filter()
和some()
const routes = ['/pageA/pageAA.html',
'/pageB.html',
'/pageC.html',
'/pageC/',
'/pageC/pageW/pageC.html',
'/'
]
const res = routes.filter(x => !x.endsWith('/') && !routes.some(a => a.endsWith('/') && x.split('.')[0] === a.replace(/\/$/,'')))
console.log(res)