简体   繁体   中英

Filter list of strings if a keyword matches in another list using Ramda

I have a list of URLs that have been returned from an API:

const data = [
  '/shoutouts',
  '/shoutouts/shoutout',
  '/news/news-story',
  '/example-page',
  '/another-page',
  '/stories/what-s-next',
  '/metrics',
  '/links',
  '/links/sprint',
  '/quick-links',
  '/quick-links/confluence'
]

And I have a some categories that I'd like to filter my URLs with:

const filters = [
  'news',
  'shoutouts',
  'quick-links',
  'metrics',
  'links'
]

I'd like to be left only with URLs that contain a category name in. For example, if one of the URLs contains links or news , we'd like to keep it.

This is the (not working) code idea I have so far.

const containsFilter = (filter, data) => R.contains(filter, data)

const filtered = R.map(filter => {
  return R.filter(containsFilter(filter, data))
}, filters)

How might I adapt this in a more pure/ramda-esque way to filter my URL list?

You can use the following:

const filtered = R.filter(url => {
  return R.any((filter) => {
    return R.contains(filter, url);
  }, filters);
}, data);

仅使用普通JS的解决方案:

const filtered = data.reduce((res, curr) => filters.some(f => curr.includes(f)) ? res.concat(curr) : res, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM