Search code examples
javascriptfunctional-programmingramda.jspure-function

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?


Solution

  • You can use the following:

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