javascript - 过滤路径数组的干净方法

标签 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)

最佳答案

您可以使用 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)

关于javascript - 过滤路径数组的干净方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55675220/

相关文章:

javascript - 如何使用搜索功能更新 Youtube 视频?

javascript - Bookshelf.js/Knex.js 嵌套在单个查询中的位置

javascript - 根据用户输入创建表单字段

javascript - react 门户 : host multiple inside same domNode parent?

javascript - 在 Javascript/jQuery Laravel 5.1 中获取当前用户

javascript - 在 body scroll 上切换 css 和 class

php - 登录系统设计允许每个用户一次登录一台机器

javascript - React-router v2.0 browserHistory 不工作

javascript - 对象内的项返回为未定义

javascript - json 数组中的项目数