过滤路径数组的干净方法

时间:2019-04-14 12:24:19

标签: javascript

如何过滤以下数组

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

1 个答案:

答案 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)